Pascal Pyramid Rows and Top-K Frequent Elements

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement solve_triangle_rows_and_top_frequencies(num_rows, nums, k), which completes two independent tasks and returns both results in a two-element list [triangle, top_values]:

  1. Pascal Pyramid Rows (triangle): Given a non-negative integer num_rows, generate rows 0 through num_rows - 1 of an additive number pyramid ([] when num_rows == 0):

    • Row r (0 <= r < num_rows) contains r + 1 integers.
    • The first entry (c = 0) and last entry (c = r) of every row equal 1.
    • Every strictly interior entry (0 < c < r) is the sum of the two adjacent entries immediately above it in row r - 1: triangle[r][c] = triangle[r - 1][c - 1] + triangle[r - 1][c].
  2. Most Frequent k Distinct Elements (top_values): Given an integer list nums and a non-negative integer k, return k distinct integers from nums that have the highest occurrence counts ([] when k == 0):

    • Count how often each distinct integer appears, then maintain a bounded min-heap of size k to track the strongest k distinct candidates rather than sorting all distinct integers.
    • Output order does not matter, and if multiple distinct integers share the cutoff frequency, any valid subset of k distinct integers achieving the top k frequencies is accepted.

Examples

Example 1

Input:  num_rows = 4, nums = [4, 9, 4, 7, 9, 4, 2, 9, 4], k = 2
Output: [[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]], [4, 9]]

Rows 0..3 of the pyramid are [1], [1, 1], [1, 2, 1], and [1, 3, 3, 1]. In nums, 4 appears 4 times, 9 appears 3 times, and 7 and 2 appear 1 time each, so the 2 most frequent distinct elements are 4 and 9.

Example 2

Input:  num_rows = 6, nums = [10, -5, 10, 8, -5, -5], k = 1
Output: [[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]], [-5]]

Row 4 is [1, 4, 6, 4, 1] and row 5 sums adjacent pairs (1+4=5, 4+6=10, 6+4=10, 4+1=5) between 1 borders to form [1, 5, 10, 10, 5, 1]. In nums, -5 appears 3 times compared with 2 for 10 and 1 for 8, making [-5] the top-1 list.

Constraints

  • 0 <= num_rows <= 200
  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= number of distinct values in nums

Step-by-step walkthrough

  1. Understand both subproblems and the output shape

    One wrapper function solves two independent problems and packs both answers into a two-item list [triangle, top_values]:

    • Problem 1 (Additive triangle): Given num_rows, build the first num_rows rows of Pascal's triangle (0-indexed). Row row_idx contains row_idx + 1 integers, starts and ends with 1, and fills each inner slot by adding the two numbers directly above it.
    • Problem 2 (Top-k frequent values): Given nums and k, return k distinct numbers from nums that appear most often. Ties can be broken in any way, and any output order is valid according to the prompt.

    Two small conventions keep our implementation clean and predictable:

    • Boundary sizes return empty lists: num_rows <= 0 produces [], and k <= 0 produces [].
    • We return top_values ordered from most frequent to least frequent. Even though the problem statement permits any order, Example 1 lists [4, 9], so ordering most-frequent-first matches the example naturally.
  2. Problem 1: Build the additive triangle row by row

    Every row after the top two depends only on the row immediately above it. Look at how each interior number in row 3 comes from two adjacent positions in row 2:

    row 0:          [1]
    row 1:        [1,  1]
    row 2:      [1,  2,  1]
                   \ / \ /
    row 3:    [1,   3,  3,   1]
               ^    ^   ^    ^
             col 0  1   2  col 3
             row[1] = prev[0] + prev[1] = 1 + 2 = 3
             row[2] = prev[1] + prev[2] = 2 + 1 = 3
    

    If we start row row_idx as [1] * (row_idx + 1), both borders (col_idx = 0 and col_idx = row_idx) are already 1. Then we only need to loop col_idx over the strictly interior indices 1 .. row_idx - 1:

    • For row_idx = 0 ([1]) and row_idx = 1 ([1, 1]), range(1, row_idx) is empty, so neither row needs an if branch.
    • Python integers have arbitrary precision, so large rows never overflow (row 34's middle entry is 2,333,606,220, which already exceeds a signed 32-bit integer).
    def build_triangle(num_rows: int) -> List[List[int]]:
        """Return the first num_rows rows of the additive (Pascal's) triangle."""
        # triangle: list of rows, e.g. [[1], [1, 1], [1, 2, 1]]; row i has length i + 1
        triangle: List[List[int]] = []
    
        for row_idx in range(num_rows):
            # Pre-fill with 1s so both endpoints (index 0 and index row_idx) are already 1.
            row = [1] * (row_idx + 1)
    
            # Fill strictly interior positions 1 .. row_idx - 1 from the row directly above.
            # For row_idx = 0 and row_idx = 1, range(1, row_idx) is empty, so no special case is needed.
            for col_idx in range(1, row_idx):
                previous_row = triangle[row_idx - 1]
                left_above = previous_row[col_idx - 1]
                right_above = previous_row[col_idx]
                row[col_idx] = left_above + right_above
    
            triangle.append(row)
    
        return triangle
    
  3. Problem 2: Count frequencies first, and see why full sorting wastes work

    Before we can compare how often numbers appear, we must count them. One pass over nums builds a dictionary counts mapping each distinct number to its frequency:

    nums = [4, 9, 4, 7, 9, 4, 2, 9, 4]  -->  counts = {4: 4, 9: 3, 7: 1, 2: 1}
    

    If nums has n elements and d distinct values, counting takes O(n) time.

    The most obvious next step is sorting all d distinct (count, value) pairs from largest to smallest and slicing the first k. That costs O(d log d) time. When d = 500,000 and k = 5, sorting spends almost all of its effort ordering the 499,995 infrequent items we are about to discard! The prompt asks us to keep only a size-k heap instead.

  4. Problem 2: Keep a size-k VIP room using a min-heap

    Imagine a VIP room with only k chairs. As each distinct (count, value) candidate walks up to the door, we only need to answer one question: "Who currently sitting inside has the lowest count?" If the room now has k + 1 people, that lowest-count person cannot possibly belong to the top k, so we evict them immediately.

    A min-heap (heapq in Python) is a binary tree stored inside a plain list where the smallest element always sits at index 0:

    • Peeking at the smallest element (min_heap[0]) takes O(1) time.
    • Pushing a new element (heappush) or popping the smallest element (heappop) takes O(log s) time on a heap of size s.

    Because we evict whenever the heap grows to k + 1 items, its size never exceeds k + 1. Processing all d distinct values therefore costs O(d log k) time and O(k) heap space!

    Notice why we use a min-heap rather than a max-heap: to guard the top k winners, we always want fast access to the weakest finalist currently kept so we can drop it in O(log k).

  5. Code the top-k frequency helper

    Pay attention to three implementation details:

    1. Loop over counts.items(), not nums: Each distinct value must enter the heap once with its final count, never multiple times.
    2. Pop when len(min_heap) > k (strictly greater): Popping at >= k would shrink the heap to k - 1 items and return one item too few.
    3. Tuple order (count, value): Python compares tuples left to right, so putting count first orders the heap by frequency (using value only as a harmless tie-breaker when two counts match). Popping empties the min-heap from smallest kept count to largest, so reversing at the end puts the highest frequency first.
    def top_k_frequent(nums: List[int], k: int) -> List[int]:
        """Return k distinct values from nums with the highest frequencies, most frequent first."""
        if k <= 0:
            return []
    
        # Phase 1: Count occurrences of each distinct value.
        # counts: dict mapping value -> frequency, e.g. {4: 4, 9: 3, 7: 1, 2: 1}
        counts: Dict[int, int] = {}
        for num in nums:
            counts[num] = counts.get(num, 0) + 1
    
        # Phase 2: Maintain a size-k min-heap of the strongest candidates seen so far.
        # min_heap: list of (count, value) tuples; min_heap[0] is always the weakest kept candidate
        min_heap: List[Tuple[int, int]] = []
        for value, count in counts.items():
            heapq.heappush(min_heap, (count, value))
            # Evict only when size exceeds k (> k, not >= k) so up to k distinct values remain.
            if len(min_heap) > k:
                heapq.heappop(min_heap)
    
        # Phase 3: Extract kept values; min-heap pops smallest count first, so reverse for descending order.
        top_values: List[int] = []
        while min_heap:
            count, value = heapq.heappop(min_heap)
            top_values.append(value)
        top_values.reverse()
        return top_values
    
  6. Trace Example 1 end to end

    Let's trace num_rows = 4, nums = [4, 9, 4, 7, 9, 4, 2, 9, 4], k = 2.

    Part 1 (build_triangle(4)):

    row_idx = 0: [1]
    row_idx = 1: [1, 1]
    row_idx = 2: [1, 1+1, 1]        -> [1, 2, 1]
    row_idx = 3: [1, 1+2, 2+1, 1]   -> [1, 3, 3, 1]
    

    Part 2 (top_k_frequent([4, 9, 4, 7, 9, 4, 2, 9, 4], 2)):

    counts = {4: 4, 9: 3, 7: 1, 2: 1}
    
    Candidate (count=4, value=4): push (4, 4) -> min_heap = [(4, 4)]           (len 1 <= 2)
    Candidate (count=3, value=9): push (3, 9) -> min_heap = [(3, 9), (4, 4)]   (len 2 <= 2, weakest at root is (3, 9))
    Candidate (count=1, value=7): push (1, 7) -> min_heap = [(1, 7), (4, 4), (3, 9)]
                                  len 3 > 2   -> pop root (1, 7) -> kept [(3, 9), (4, 4)]
    Candidate (count=1, value=2): push (1, 2) -> min_heap = [(1, 2), (4, 4), (3, 9)]
                                  len 3 > 2   -> pop root (1, 2) -> kept [(3, 9), (4, 4)]
    
    Pop all:  1st pop -> (3, 9) -> append 9
              2nd pop -> (4, 4) -> append 4
    Reverse [9, 4] -> [4, 9]
    

    Combining both parts gives [[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]], [4, 9]].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    def build_triangle(num_rows: int) -> List[List[int]]:
        """Return the first num_rows rows of the additive (Pascal's) triangle."""
        # triangle: list of rows, e.g. [[1], [1, 1], [1, 2, 1]]; row i has length i + 1
        triangle: List[List[int]] = []
    
        for row_idx in range(num_rows):
            # Pre-fill with 1s so both endpoints (index 0 and index row_idx) are already 1.
            row = [1] * (row_idx + 1)
    
            # Fill strictly interior positions 1 .. row_idx - 1 from the row directly above.
            # For row_idx = 0 and row_idx = 1, range(1, row_idx) is empty, so no special case is needed.
            for col_idx in range(1, row_idx):
                previous_row = triangle[row_idx - 1]
                left_above = previous_row[col_idx - 1]
                right_above = previous_row[col_idx]
                row[col_idx] = left_above + right_above
    
            triangle.append(row)
    
        return triangle
    
    
    def top_k_frequent(nums: List[int], k: int) -> List[int]:
        """Return k distinct values from nums with the highest frequencies, most frequent first."""
        if k <= 0:
            return []
    
        # Phase 1: Count occurrences of each distinct value.
        # counts: dict mapping value -> frequency, e.g. {4: 4, 9: 3, 7: 1, 2: 1}
        counts: Dict[int, int] = {}
        for num in nums:
            counts[num] = counts.get(num, 0) + 1
    
        # Phase 2: Maintain a size-k min-heap of the strongest candidates seen so far.
        # min_heap: list of (count, value) tuples; min_heap[0] is always the weakest kept candidate
        min_heap: List[Tuple[int, int]] = []
        for value, count in counts.items():
            heapq.heappush(min_heap, (count, value))
            # Evict only when size exceeds k (> k, not >= k) so up to k distinct values remain.
            if len(min_heap) > k:
                heapq.heappop(min_heap)
    
        # Phase 3: Extract kept values; min-heap pops smallest count first, so reverse for descending order.
        top_values: List[int] = []
        while min_heap:
            count, value = heapq.heappop(min_heap)
            top_values.append(value)
        top_values.reverse()
        return top_values
    
    
    def solve_triangle_rows_and_top_frequencies(num_rows: int, nums: List[int], k: int) -> List[List[int]]:
        triangle = build_triangle(num_rows)
        top_values = top_k_frequent(nums, k)
        return [triangle, top_values]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

This assessment pairs two classic building blocks into a single function:

  1. Stacking bricks row by row (Pascal's triangle): Imagine building a pyramid of numbered bricks where both outer edges are always 1, and every inner brick displays the sum of the two bricks directly supporting it from the row above. That pyramid is called Pascal's triangle (a triangular table whose j-th entry in row i also equals the binomial coefficient C(i, j), the number of ways to choose j items out of i).
  2. Guarding a k-seat VIP room (top-k frequencies): Imagine tallying votes on a whiteboard and then keeping only the top k winners in a small room with k chairs. Instead of sorting every candidate in town, a bouncer uses a min-heap (a tree-in-a-list data structure that always keeps the smallest item at index 0 for instant lookup and logarithmic removal) so whenever k + 1 candidates are inside, the weakest one is immediately shown the door.

Why avoid the naive shortcuts? For the triangle, computing every cell independently with factorials i! / (j! * (i - j)!) repeats multiplications that a simple addition from the previous row gets in one step (and floating-point division loses exactness on large rows). For top-k frequencies, sorting all d distinct values takes O(d log d) comparisons to rank thousands of low-frequency items we immediately throw away, whereas a size-k min-heap never compares more than k + 1 items at a time.

Here is a quick trace on num_rows = 4 and nums = [7, 7, 8, 8, 8, 9], k = 2:

Triangle (4 rows):
  row 0: [1]
  row 1: [1, 1]
  row 2: [1, 1+1, 1]        -> [1, 2, 1]
  row 3: [1, 1+2, 2+1, 1]   -> [1, 3, 3, 1]

Top-2 frequencies:
  1. Count values: {7: 2, 8: 3, 9: 1}
  2. Push (2, 7) -> heap = [(2, 7)]
  3. Push (3, 8) -> heap = [(2, 7), (3, 8)]           (root (2, 7) is weakest of top 2)
  4. Push (1, 9) -> size is 3 > 2 -> pop root (1, 9)  (heap stays [(2, 7), (3, 8)])
  5. Pop & reverse -> [8, 7]

Complexity

Let R = num_rows, n = len(nums), and d be the number of distinct values in nums (d <= n).

  • Triangle time: O(R^2). Row i fills i + 1 slots with one addition per interior slot, so across rows 0 .. R - 1 we perform 1 + 2 + ... + R = R * (R + 1) / 2 constant-time cell writes—optimal because the output itself contains O(R^2) numbers. (For very large R, numbers grow to roughly R bits wide, so big-integer addition gradually scales with R as well.)
  • Triangle space: O(R^2). All R * (R + 1) / 2 integers belong to the returned list of rows, with no auxiliary tables needed.
  • Top-k time: O(n + d log k). Scanning nums once builds the counts dictionary in O(n) average time; we then push each of the d distinct pairs onto a heap whose size never exceeds k + 1 (O(log k) per push/pop), and finally pop k winners in O(k log k) (k <= d).
  • Top-k space: O(d + k). The counts dictionary stores one entry per distinct value (O(d)), and min_heap holds at most k + 1 tuples at any moment (O(k)).

Edge cases

  • num_rows = 0: range(0) never runs, returning an empty triangle [].
  • num_rows = 1 or 2: Returns [[1]] and [[1], [1, 1]]; range(1, row_idx) is empty for row_idx = 0 and 1, so border rows work with zero special cases.
  • 32-bit and 64-bit integer growth: Row 34's center value C(34, 17) = 2,333,606,220 already overflows a signed 32-bit integer, and row 67's center value C(67, 33) overflows a signed 64-bit integer. Python's arbitrary-precision int handles this automatically, while C++ or Java solutions must choose long / BigInteger accordingly.
  • Tied frequencies: When [1, 2, 3, 1, 2, 3, 4] asks for k = 2, any two of {1, 2, 3} have counts [2, 2] and are accepted.
  • k equal to distinct count (k == d): The heap never overflows k, returning every distinct number once.
  • k = 0: Guarded upfront to return [] without touching nums.
  • Negative integers in nums: Python hashes negative integers into counts and compares (count, value) tuples cleanly regardless of sign.

Common mistakes

  • Updating a single triangle row in place from left to right: If you reuse one array and run row[j] += row[j - 1] left-to-right, row[j - 1] has already been overwritten with the new row's sum! Either read from triangle[row_idx - 1] (as we do) or iterate right-to-left when mutating in place.
  • Off-by-one inner loop range(1, row_idx + 1): Including col_idx = row_idx tries to read previous_row[row_idx], which raises IndexError because previous_row only has indices 0 .. row_idx - 1.
  • Pushing directly while looping over nums instead of counts.items(): Pushing raw elements from nums inserts the same popular number into the heap multiple times, producing duplicate values in the output.
  • Evicting when len(min_heap) >= k instead of > k: Popping at size k leaves at most k - 1 elements in the heap, returning one fewer answer than requested.
  • Putting value before count in the heap tuple: (value, count) orders the heap by the number itself rather than how often it occurred; count must come first as (count, value).

Alternative approaches

  • Bucket sort by frequency (O(n) time, O(n) space): Bucket sort groups items into an array of lists indexed directly by an integer key; since any element in nums appears between 1 and n times, we can place each value into buckets[count] and scan buckets downward from n to 1 until we collect k values.
  • Quickselect (O(n + d) average time, O(d) space): Quickselect is Hoare's partitioning algorithm (the cousin of quicksort that recurses into only one side of the pivot) to move the k highest-count pairs to one side in linear average time, though its worst case is O(d^2) on unlucky pivots.
  • collections.Counter(nums).most_common(k): Python's standard library helper uses heapq.nlargest under the hood with the same O(n + d log k) bound, though interviewers specifically ask to see the explicit size-k min-heap loop here.

Follow-up questions

  • If you only needed row r of the triangle rather than all rows up to r, how could you compute it using O(r) memory? Maintain a single list row initialized to [1] and grow it step by step, updating inner indices from right to left (for j in range(len(row) - 1, 0, -1): row[j] += row[j - 1]) before appending 1 so you never overwrite a value before reading it. Even faster, compute row r directly in O(r) time using the multiplicative identity C(r, j) = C(r, j - 1) * (r - j + 1) // j, which stays exact in integer division at every step.
  • Under what input distributions is frequency bucket sort preferable to a size-k min-heap, and when does the min-heap win? Bucket sort wins on asymptotic time (O(n) vs O(n + d log k)) when nums fits comfortably in memory as an array of n + 1 buckets. However, if counts come pre-aggregated (say d = 10,000 products whose total purchase counts sum to n = 10^12), allocating 10^12 buckets is impossible while the size-k min-heap still finishes in O(d log k) time and O(k) space.
  • How would your design change if nums arrived as an unbounded stream whose distinct elements could not all fit in RAM? Exact top-k over an arbitrary stream requires O(d) memory in the worst case because an early rare item could surge later. To stay in bounded memory, you can use a heavy-hitters sketch such as Misra-Gries (which maintains m candidate counters and guarantees keeping every item whose frequency exceeds n / (m + 1)) or a Count-Min sketch (a small 2D table of hash counters that estimates frequencies with bounded overcounting) paired with a size-k min-heap.

Follow-up questions

Similar questions

More Ericsson interview questions

All 1 Ericsson questions →