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]:
-
Pascal Pyramid Rows (
triangle): Given a non-negative integernum_rows, generate rows0throughnum_rows - 1of an additive number pyramid ([]whennum_rows == 0):- Row
r(0 <= r < num_rows) containsr + 1integers. - The first entry (
c = 0) and last entry (c = r) of every row equal1. - Every strictly interior entry (
0 < c < r) is the sum of the two adjacent entries immediately above it in rowr - 1:triangle[r][c] = triangle[r - 1][c - 1] + triangle[r - 1][c].
- Row
-
Most Frequent
kDistinct Elements (top_values): Given an integer listnumsand a non-negative integerk, returnkdistinct integers fromnumsthat have the highest occurrence counts ([]whenk == 0):- Count how often each distinct integer appears, then maintain a bounded min-heap of size
kto track the strongestkdistinct 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
kdistinct integers achieving the topkfrequencies is accepted.
- Count how often each distinct integer appears, then maintain a bounded min-heap of size
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 <= 2000 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^90 <= k <=number of distinct values innums
Step-by-step walkthrough
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 firstnum_rowsrows of Pascal's triangle (0-indexed). Rowrow_idxcontainsrow_idx + 1integers, starts and ends with1, and fills each inner slot by adding the two numbers directly above it. - Problem 2 (Top-k frequent values): Given
numsandk, returnkdistinct numbers fromnumsthat 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 <= 0produces[], andk <= 0produces[]. - We return
top_valuesordered 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.
- Problem 1 (Additive triangle): Given
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
3comes from two adjacent positions in row2: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 = 3If we start row
row_idxas[1] * (row_idx + 1), both borders (col_idx = 0andcol_idx = row_idx) are already1. Then we only need to loopcol_idxover the strictly interior indices1 .. row_idx - 1:- For
row_idx = 0([1]) androw_idx = 1([1, 1]),range(1, row_idx)is empty, so neither row needs anifbranch. - 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- For
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
numsbuilds a dictionarycountsmapping 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
numshasnelements andddistinct values, counting takesO(n)time.The most obvious next step is sorting all
ddistinct(count, value)pairs from largest to smallest and slicing the firstk. That costsO(d log d)time. Whend = 500,000andk = 5, sorting spends almost all of its effort ordering the499,995infrequent items we are about to discard! The prompt asks us to keep only a size-kheap instead.Problem 2: Keep a size-k VIP room using a min-heap
Imagine a VIP room with only
kchairs. 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 hask + 1people, that lowest-count person cannot possibly belong to the topk, so we evict them immediately.A min-heap (
heapqin Python) is a binary tree stored inside a plain list where the smallest element always sits at index0:- Peeking at the smallest element (
min_heap[0]) takesO(1)time. - Pushing a new element (
heappush) or popping the smallest element (heappop) takesO(log s)time on a heap of sizes.
Because we evict whenever the heap grows to
k + 1items, its size never exceedsk + 1. Processing allddistinct values therefore costsO(d log k)time andO(k)heap space!Notice why we use a min-heap rather than a max-heap: to guard the top
kwinners, we always want fast access to the weakest finalist currently kept so we can drop it inO(log k).- Peeking at the smallest element (
Code the top-k frequency helper
Pay attention to three implementation details:
- Loop over
counts.items(), notnums: Each distinct value must enter the heap once with its final count, never multiple times. - Pop when
len(min_heap) > k(strictly greater): Popping at>= kwould shrink the heap tok - 1items and return one item too few. - Tuple order
(count, value): Python compares tuples left to right, so puttingcountfirst orders the heap by frequency (usingvalueonly 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- Loop over
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]].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:
- 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 whosej-th entry in rowialso equals the binomial coefficientC(i, j), the number of ways to choosejitems out ofi). - Guarding a
k-seat VIP room (top-k frequencies): Imagine tallying votes on a whiteboard and then keeping only the topkwinners in a small room withkchairs. 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 index0for instant lookup and logarithmic removal) so wheneverk + 1candidates 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). Rowifillsi + 1slots with one addition per interior slot, so across rows0 .. R - 1we perform1 + 2 + ... + R = R * (R + 1) / 2constant-time cell writes—optimal because the output itself containsO(R^2)numbers. (For very largeR, numbers grow to roughlyRbits wide, so big-integer addition gradually scales withRas well.) - Triangle space:
O(R^2). AllR * (R + 1) / 2integers belong to the returned list of rows, with no auxiliary tables needed. - Top-k time:
O(n + d log k). Scanningnumsonce builds thecountsdictionary inO(n)average time; we then push each of theddistinct pairs onto a heap whose size never exceedsk + 1(O(log k)per push/pop), and finally popkwinners inO(k log k)(k <= d). - Top-k space:
O(d + k). Thecountsdictionary stores one entry per distinct value (O(d)), andmin_heapholds at mostk + 1tuples at any moment (O(k)).
Edge cases
num_rows = 0:range(0)never runs, returning an empty triangle[].num_rows = 1or2: Returns[[1]]and[[1], [1, 1]];range(1, row_idx)is empty forrow_idx = 0and1, 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,220already overflows a signed 32-bit integer, and row 67's center valueC(67, 33)overflows a signed 64-bit integer. Python's arbitrary-precisioninthandles this automatically, while C++ or Java solutions must chooselong/BigIntegeraccordingly. - Tied frequencies: When
[1, 2, 3, 1, 2, 3, 4]asks fork = 2, any two of{1, 2, 3}have counts[2, 2]and are accepted. kequal to distinct count (k == d): The heap never overflowsk, returning every distinct number once.k = 0: Guarded upfront to return[]without touchingnums.- Negative integers in
nums: Python hashes negative integers intocountsand 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 fromtriangle[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): Includingcol_idx = row_idxtries to readprevious_row[row_idx], which raisesIndexErrorbecauseprevious_rowonly has indices0 .. row_idx - 1. - Pushing directly while looping over
numsinstead ofcounts.items(): Pushing raw elements fromnumsinserts the same popular number into the heap multiple times, producing duplicate values in the output. - Evicting when
len(min_heap) >= kinstead of> k: Popping at sizekleaves at mostk - 1elements in the heap, returning one fewer answer than requested. - Putting
valuebeforecountin the heap tuple:(value, count)orders the heap by the number itself rather than how often it occurred;countmust 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 innumsappears between1andntimes, we can place each value intobuckets[count]and scanbucketsdownward fromnto1until we collectkvalues. - 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 thekhighest-count pairs to one side in linear average time, though its worst case isO(d^2)on unlucky pivots. collections.Counter(nums).most_common(k): Python's standard library helper usesheapq.nlargestunder the hood with the sameO(n + d log k)bound, though interviewers specifically ask to see the explicit size-kmin-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
rowinitialized 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 appending1so you never overwrite a value before reading it. Even faster, compute rowrdirectly inO(r)time using the multiplicative identityC(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)vsO(n + d log k)) whennumsfits comfortably in memory as an array ofn + 1buckets. However, if counts come pre-aggregated (sayd = 10,000products whose total purchase counts sum ton = 10^12), allocating10^12buckets is impossible while the size-kmin-heap still finishes inO(d log k)time andO(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 maintainsmcandidate counters and guarantees keeping every item whose frequency exceedsn / (m + 1)) or a Count-Min sketch (a small 2D table of hash counters that estimates frequencies with bounded overcounting) paired with a size-kmin-heap.
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?
- Under what input distributions is frequency bucket sort preferable to a size-k min-heap, and when does the min-heap win?
- How would your design change if nums arrived as an unbounded stream whose distinct elements could not all fit in RAM?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array