Top K Elements via Partition Selection
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given an integer array values and an integer k, implement:
def largest_k(values: List[int], k: int) -> List[int]:
Your function should select the k greatest occurrences from values and return them arranged from largest to smallest.
Follow these rules and design goals:
- Every occurrence counts: Do not deduplicate equal numbers. If the maximum value appears multiple times, include up to
kcopies of it so the returned list always has lengthk. - Boundary counts: When
k == 0, return[]. Whenk == len(values), return every element ofvaluesordered from largest to smallest. - Partition-first selection: Isolate the
klargest occurrences via Quickselect-style partitioning so the unselectedlen(values) - kitems never need to be sorted against one another, then sort only thekchosen items for an expectedO(n + k log k)runtime. - Memory & trade-offs: You may partition
valuesdirectly or copy it first if you account for theO(n)extra space. Be ready to discuss pivot strategy, duplicate-heavy inputs, worst-case quadratic behavior in naive Quickselect, and when anO(n log k)min-heap orO(n log n)full sort is preferable (such as unbounded streams or very smallk).
Examples
Example 1
Input: values = [5, 12, 4, 12, 8, 2], k = 3
Output: [12, 12, 8]
Both occurrences of 12 are kept separately, followed by the next largest element 8. The remaining elements (5, 4, and 2) fall below the top-3 cutoff and do not need to be sorted.
Example 2
Input: values = [-8, -2, -6, -5], k = 2
Output: [-2, -5]
Among negative integers, -2 is the greatest and -5 is the second greatest, so returning the top 2 items in descending order gives [-2, -5].
Constraints
0 <= len(values) <= 200,0000 <= k <= len(values)-2^31 <= values[i] <= 2^31 - 1
Step-by-step walkthrough
Separate selection from sorting
We are given a list
valuesof lengthn(0 <= n <= 200,000) and an integerk(0 <= k <= n), and we want theklargest occurrences returned in descending order:- Duplicates count separately:
[5, 12, 4, 12, 8, 2]withk = 3returns[12, 12, 8], keeping both12s. - Boundary cases:
k = 0returns[];k = nreturns allnnumbers sorted descending.
The central insight is that this task splits into two independent jobs:
- Selection: find the cutoff between the
klargest occurrences and then - ksmaller ones, placing thosekwinners intoarr[:k]in any order. - Output sorting: sort only those
kwinners descending (O(k log k)).
Nothing in the problem asks us to order the
n - kdiscarded elements against each other.- Duplicates count separately:
Compare full sort, min-heap, and quickselect
Before coding, let's compare the three standard ways to get the top
kelements so we understand when each wins:Approach Time Extra space Streaming? Best when... ------------------------- -------------------- ----------- ---------- ---------------------------- Full sort + slice [:k] O(n log n) O(n) No Code simplicity or k ≈ n Min-heap of size k O(n log k) O(k) Yes Tiny k (e.g. k <= 20) or stream 3-way quickselect + sort O(n + k log k) avg O(n) copy* No Array in RAM, general k O(n^2) worst case (*O(1) in-place)- Full sort (
sorted(values, reverse=True)[:k]) doesO(n log n)work even whenk = 5, spending almost all its effort sortingn - klosers. - Min-heap of size
kkeeps theklargest elements seen so far, with the smallest of thoseksitting at the root. Each incoming element either skips the heap inO(1)or replaces the root inO(log k). That givesO(n log k)time andO(k)memory, and works in a single streaming pass — ideal whenkis tiny or data does not fit in memory, though whenkgrows close ton,O(n log k)approachesO(n log n). - Partition-based selection (quickselect) finds the
kwinners in expectedO(n)time by repeatedly partitioning only the subarray that contains indexk - 1, then sorts justarr[:k]inO(k log k).
- Full sort (
Key idea: three-way partitioning around a random pivot
Suppose we pick a
pivotvalue inside our active subarrayarr[lo..hi]and rearrangearr[lo..hi]into three contiguous blocks:[ strictly > pivot | == pivot | strictly < pivot ] lo .. eq_start-1 eq_start..eq_end-1 eq_end .. hiWhere does the last selected slot
target_idx = k - 1land?- Inside
> pivot(target_idx < eq_start): There are already more thankelements larger thanpivot, so we throw away the== pivotand< pivotblocks (hi = eq_start - 1). - Inside
== pivot(eq_start <= target_idx < eq_end): Every slot beforekis>= pivotand every slot fromkonward is<= pivot.arr[:k]already holds the exactklargest occurrences — we stop! - Inside
< pivot(target_idx >= eq_end): Everything in> pivotand== pivotdefinitely belongs in the topk, so we lock them in and continue searching only inside< pivot(lo = eq_end).
Unlike quicksort, which recurses into both sides, quickselect follows at most one side per round! Two choices protect us against classic
O(n^2)traps:- Random pivot (
random.randint(lo, hi)): Always pickingarr[lo]degrades toO(n^2)on sorted or reverse-sorted arrays because each round trims only1element. A random pivot lands in the middle half of the window with probability1/2, shrinking the window geometrically forO(n)expected total work (while still having a theoreticalO(n^2)worst case if random draws are maximally unlucky every round). - Three-way partition instead of two-way: If all
50,000elements equal7, a naive two-way partition pushes49,999copies to one side and takes quadratic time. Three-way partitioning groups all50,000copies into== pivotand finishes in one single pass.
- Inside
Code the Dutch National Flag partition
To partition
arr[lo..hi]into> pivot,== pivot, and< pivotin one pass withO(1)extra variables, we maintain three pointers (gt_end,i,lt_start) dividingarr[lo..hi]into four zones:lo gt_end i lt_start hi | > pivot | == pivot | unseen | < pivot |As
iscans across the unseen zone (while i <= lt_start:):arr[i] > pivot: Swaparr[gt_end]andarr[i], then increment bothgt_endandi. Why is advancingisafe here? Becausearr[gt_end]came from the== pivotzone (orgt_end == i), so we already know what swapped intoarr[i].arr[i] < pivot: Swaparr[i]andarr[lt_start], and decrementlt_start— without advancingi! Why keepistill? Because the number swapped in fromarr[lt_start]came from the right edge of the unseen zone and still needs to be inspected on the next iteration.arr[i] == pivot: Leave it in place and advanceito grow the== pivotzone.
def _partition_three_way(arr: List[int], lo: int, hi: int, pivot: int) -> Tuple[int, int]: """Split arr[lo : hi + 1] into three zones around `pivot`: arr[lo : eq_start] > pivot, arr[eq_start : eq_end] == pivot, arr[eq_end : hi + 1] < pivot. """ # Loop invariant across four slices of arr[lo : hi + 1]: # arr[lo : gt_end] -> strictly > pivot # arr[gt_end : i] -> equal to pivot # arr[i : lt_start + 1] -> not inspected yet # arr[lt_start + 1 : hi + 1] -> strictly < pivot gt_end = lo i = lo lt_start = hi while i <= lt_start: current = arr[i] if current > pivot: # Swap into the "> pivot" zone and advance both pointers; # `arr[gt_end]` was either `current` itself (gt_end == i) or already verified `== pivot`. arr[gt_end], arr[i] = arr[i], arr[gt_end] gt_end += 1 i += 1 elif current < pivot: # Swap into the "< pivot" zone at the right edge. # Do NOT advance `i` yet because the element swapped in from `lt_start` is still unseen! arr[i], arr[lt_start] = arr[lt_start], arr[i] lt_start -= 1 else: # `current == pivot`: simply extend the "== pivot" middle zone. i += 1 eq_start = gt_end eq_end = lt_start + 1 return eq_start, eq_endCode the quickselect loop and k-element sort
Now we wrap
_partition_three_wayinsidelargest_k:- Handle
k <= 0immediately (return []), sincetarget_idx = k - 1only exists whenk >= 1. - Copy
valuesintoarr = list(values)so the caller's list is never scrambled (O(n)extra space; if an interviewer asks forO(1)auxiliary space, partitionvaluesdirectly). - Narrow
[lo, hi]aroundtarget_idx = k - 1untileq_start <= target_idx < eq_end. Notice how ties across indexk - 1resolve effortlessly: if three4s span indices2, 3, 4andk = 4(target_idx = 3),arr[:4]takes two of the4s and leaves the third behind. - Slice
selected = arr[:k]and sort only thosekitems descending.
def largest_k(values: List[int], k: int) -> List[int]: # Guard k == 0 first because there is no boundary index `k - 1` when 0 items are chosen. if k <= 0: return [] # Work on a copy (`O(n)` extra memory) so we never mutate the caller's input list. arr = list(values) # Phase 1 (Selection): Quickselect until `arr[:k]` holds the k largest occurrences # in any order. Boundary index `target_idx = k - 1` stays inside `arr[lo : hi + 1]`. target_idx = k - 1 lo = 0 hi = len(arr) - 1 while lo <= hi: # Random pivot prevents sorted or reversed inputs from triggering O(n^2) behavior. pivot = arr[random.randint(lo, hi)] eq_start, eq_end = _partition_three_way(arr, lo, hi, pivot) if target_idx < eq_start: # Boundary sits inside the "> pivot" zone; discard "== pivot" and "< pivot". hi = eq_start - 1 elif target_idx < eq_end: # Boundary sits inside the "== pivot" zone (`eq_start <= target_idx < eq_end`), # so `arr[:k]` now contains the exact k largest occurrences! break else: # Everything before `eq_end` belongs in the top k; narrow to the "< pivot" zone. lo = eq_end # Phase 2 (Output ordering): Sort ONLY the k selected occurrences (`O(k log k)`), not all n. selected = arr[:k] selected.sort(reverse=True) return selected- Handle
Trace Example 1 step by step
Let's trace
values = [5, 12, 4, 12, 8, 2]withk = 3, sotarget_idx = k - 1 = 2,lo = 0,hi = 5. Supposerandom.randint(0, 5)picks index4, givingpivot = 8:Pointers Array Comparison & action ------------------- ---------------------- -------------------------------------------- gt=0, i=0, lt=5 [5, 12, 4, 12, 8, 2] arr[0]=5 < 8 -> swap(0, 5), lt=4 (i stays 0!) gt=0, i=0, lt=4 [2, 12, 4, 12, 8, 5] arr[0]=2 < 8 -> swap(0, 4), lt=3 (i stays 0!) gt=0, i=0, lt=3 [8, 12, 4, 12, 2, 5] arr[0]=8 == 8 -> i=1 gt=0, i=1, lt=3 [8, 12, 4, 12, 2, 5] arr[1]=12 > 8 -> swap(0, 1), gt=1, i=2 gt=1, i=2, lt=3 [12, 8, 4, 12, 2, 5] arr[2]=4 < 8 -> swap(2, 3), lt=2 (i stays 2!) gt=1, i=2, lt=2 [12, 8, 12, 4, 2, 5] arr[2]=12 > 8 -> swap(1, 2), gt=2, i=3 gt=2, i=3 > lt=2 [12, 12, 8, 4, 2, 5] stop! eq_start=2, eq_end=3Now we check where
target_idx = 2sits:eq_start = 2 <= target_idx = 2 < eq_end = 3, sotarget_idxlanded inside the== 8block!- Selection stops immediately.
arr[:3]is[12, 12, 8]. - Sorting only those
3items descending yields[12, 12, 8], while the unselected tail[4, 2, 5]at indices3..5is left completely unsorted.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import random def _partition_three_way(arr: List[int], lo: int, hi: int, pivot: int) -> Tuple[int, int]: """Split arr[lo : hi + 1] into three zones around `pivot`: arr[lo : eq_start] > pivot, arr[eq_start : eq_end] == pivot, arr[eq_end : hi + 1] < pivot. """ # Loop invariant across four slices of arr[lo : hi + 1]: # arr[lo : gt_end] -> strictly > pivot # arr[gt_end : i] -> equal to pivot # arr[i : lt_start + 1] -> not inspected yet # arr[lt_start + 1 : hi + 1] -> strictly < pivot gt_end = lo i = lo lt_start = hi while i <= lt_start: current = arr[i] if current > pivot: # Swap into the "> pivot" zone and advance both pointers; # `arr[gt_end]` was either `current` itself (gt_end == i) or already verified `== pivot`. arr[gt_end], arr[i] = arr[i], arr[gt_end] gt_end += 1 i += 1 elif current < pivot: # Swap into the "< pivot" zone at the right edge. # Do NOT advance `i` yet because the element swapped in from `lt_start` is still unseen! arr[i], arr[lt_start] = arr[lt_start], arr[i] lt_start -= 1 else: # `current == pivot`: simply extend the "== pivot" middle zone. i += 1 eq_start = gt_end eq_end = lt_start + 1 return eq_start, eq_end def largest_k(values: List[int], k: int) -> List[int]: # Guard k == 0 first because there is no boundary index `k - 1` when 0 items are chosen. if k <= 0: return [] # Work on a copy (`O(n)` extra memory) so we never mutate the caller's input list. arr = list(values) # Phase 1 (Selection): Quickselect until `arr[:k]` holds the k largest occurrences # in any order. Boundary index `target_idx = k - 1` stays inside `arr[lo : hi + 1]`. target_idx = k - 1 lo = 0 hi = len(arr) - 1 while lo <= hi: # Random pivot prevents sorted or reversed inputs from triggering O(n^2) behavior. pivot = arr[random.randint(lo, hi)] eq_start, eq_end = _partition_three_way(arr, lo, hi, pivot) if target_idx < eq_start: # Boundary sits inside the "> pivot" zone; discard "== pivot" and "< pivot". hi = eq_start - 1 elif target_idx < eq_end: # Boundary sits inside the "== pivot" zone (`eq_start <= target_idx < eq_end`), # so `arr[:k]` now contains the exact k largest occurrences! break else: # Everything before `eq_end` belongs in the top k; narrow to the "< pivot" zone. lo = eq_end # Phase 2 (Output ordering): Sort ONLY the k selected occurrences (`O(k log k)`), not all n. selected = arr[:k] selected.sort(reverse=True) return selected✅ Submit now — all tests should pass.
Intuition & how it works
Imagine 200,000 runners finishing a marathon when you only need to award medals to the fastest k: you do not need to figure out who placed 150,001st versus 150,002nd — you only need to herd the top k finishers to the front of the field and then line up just those k runners in descending order! We find those k winners using quickselect (a selection algorithm that repeatedly splits an array around a chosen pivot value and discards whichever side cannot contain the k-th slot), powered by three-way partitioning (also called the Dutch National Flag scan, which rearranges a subarray in one pass into [ > pivot | == pivot | < pivot ]).
Why not just sort everything or use naive two-way partitioning? Sorting all n values costs O(n log n) time because it orders all n - k rejected items too, while a min-heap (a binary tree that tracks the k largest values seen so far with the smallest of them at the top) costs O(n log k) time, which degrades to O(n log n) when k is a large fraction of n. Naive quickselect has two famous O(n^2) traps of its own: picking a fixed pivot like arr[lo] shrinks a sorted array by only 1 item per pass, and two-way partitioning shrinks an all-equal array ([7, 7, ..., 7]) by only 1 item per pass — both of which vanish once we combine a random pivot with three-way partitioning.
Here is a trace on values = [5, 12, 4, 12, 8, 2] with k = 3 (target boundary index k - 1 = 2):
Start: [5, 12, 4, 12, 8, 2], want index 2 inside top-3 slice arr[:3]
Pick random pivot 8: partition into [ > 8 | == 8 | < 8 ]
After 1 pass: [12, 12 | 8 | 4, 2, 5] (eq_start = 2, eq_end = 3)
Check index 2: 2 sits inside [2, 3) (the "== 8" zone) -> selection done!
Sort only arr[:3]: sorted([12, 12, 8], reverse=True) -> [12, 12, 8]
Complexity
Let n be len(values) and k be the requested count.
- Time: expected
O(n + k log k), worst-caseO(n^2). Each call to_partition_three_wayscansarr[lo..hi]once in time proportional to the current window length. Because a random pivot lands in the middle half of the window with probability1/2, the window shrinks by a constant factor (at least3/4on average every two rounds), so expected selection work is a geometric seriesn + (3/4)n + (3/4)^2 n + ... = O(n). Afterward, sortingarr[:k]takesO(k log k). In the astronomically unlikely worst case where random pivots repeatedly pick the extreme element every round, selection takesO(n^2)(no fixed input pattern — sorted, reversed, or all-equal — can force this). - Space:
O(n)extra to copyvalues, plusO(k)for the returned list. Copyingarr = list(values)preserves the caller's input list, and our iterativewhileloop usesO(1)pointer variables with zero recursion stack. If mutatingvaluesin place is allowed, auxiliary selection space drops toO(1).
Edge cases
k == 0(includingvalues = []): Returns[]immediately before computingtarget_idx = k - 1 = -1.k == len(values):target_idx = n - 1selects allnitems, and Phase 2 returns the entire list sorted descending.- Duplicates and boundary ties (
[4, 9, 4, 1, 4, 7],k = 4): Duplicates are never deduplicated; when multiple copies of4straddle indexk - 1 = 3, the== 4zone covers index3andarr[:4]cleanly keeps[9, 7, 4, 4]. - All elements equal (
50,000copies of7): Three-way partitioning puts all50,000items into== pivot(eq_start = 0, eq_end = 50000) and exits on the very first round inO(n)time. - Already sorted or reverse-sorted inputs: Random pivot selection breaks input order so expected runtime stays
O(n + k log k). - Signed 32-bit extremes (
-2^31and2^31 - 1): Only<and>comparisons are performed (never arithmetic likea - b), so integer overflow is impossible even in fixed-width languages.
Common mistakes
- Deduplicating with
set(values): Example 1 requires[12, 12, 8], not[12, 8, 5]; each occurrence counts separately. - Advancing
iafter swappingarr[i]witharr[lt_start]: The element swapped in fromlt_starthas not been compared againstpivotyet; incrementingiskips it and corrupts the partition. - Using a deterministic pivot (
arr[lo]orarr[hi]): Adversarially ordered or already-sorted inputs triggerO(n^2)behavior deterministically. - Using two-way Lomuto partitioning on duplicate-heavy inputs: Sending all
== pivotvalues to one side causesO(n^2)runtime when most values are identical. - Off-by-one on the boundary index:
kitems occupy indices0 .. k - 1, so the boundary slot isk - 1, notk. - Sorting all of
arrat the end instead ofarr[:k]: Callingarr.sort(reverse=True)throws away theO(n)selection win and reverts total runtime toO(n log n).
Alternative approaches
- Min-heap of size
k(heapq.nlargest): Maintain a min-heap holding theklargest values seen so far; for each newx, ifx > heap[0], replace the root inO(log k). This runs inO(n log k)time andO(k)memory without copying or modifyingvalues, making it superior whenkis very small (k << n) or when values arrive as an unbounded stream. - Full sort (
sorted(values, reverse=True)[:k]): TakesO(n log n)time andO(n)space. In Python,Timsortruns in fast C code, so for modestnor whenkis close ton(k log k ≈ n log n) it is competitive in wall-clock time, though asymptotically slower whenk << n. - Introselect / Median of medians: Median of medians deterministically picks a pivot guaranteed to eliminate at least
30%of the window per round for strict worst-caseO(n)time (with a high constant factor). Introselect (used by C++std::nth_elementandnumpy.partition) starts with fast quickselect and switches to median-of-medians only if partitioning makes poor progress.
Follow-up questions
- When is a min-heap preferable to quickselect in real systems? Choose a min-heap whenever
valuesarrives as a stream that cannot fit in RAM, whenever callers forbid both mutating and copying anO(n)array (O(k)heap memory vsO(n)copy), or whenkis tiny (sayk = 10out of10^7items, where one sequential read pass withO(log 10)register-cache heap ops beats random-access array writes). Choose quickselect when the data already lives in memory andkcan be moderate or large (k = 50,000), whereO(n + k log k)avoidsnheap operations of costO(log k). - How can you eliminate quickselect's quadratic worst case while keeping its fast average performance? Use introselect: track a recursion/iteration budget (such as
2 * floor(log2(n))rounds or requiring the window size to shrink by at least a constant fraction every few steps), using random pivots normally and falling back to median of medians (grouping elements into5s, taking each group's median, and selecting the median of those medians as the pivot) only if random draws stall. That guaranteesO(n)selection even against a worst-case RNG trace while keeping zero overhead on normal runs. - How would you compute the global top k across data sharded over M machines? Have each machine run local selection (
largest_kor a size-kmin-heap) on its shard to emit at mostklocal winners in descending order, then send thoseMsorted lists (at mostM * knumbers total) to a coordinator that merges them with ak-step k-way merge (or anotherlargest_kcall). This is exact because no item outside a shard's local topkcan ever place in the global topk.
Follow-up questions
- When is a min-heap preferable to quickselect in real systems?
- How can you eliminate quickselect's quadratic worst case while keeping its fast average performance?
- How would you compute the global top k across data sharded over M machines?
Similar questions
- Verifying an RTL Block with a SystemVerilog UVM Testbench
- Debugging Singly Linked-List Insertion and Tracing C++ Method Dispatch
- Single-Agent Versus Multi-Agent Orchestration Architectures
- Constant-Time Fixed-Capacity LRU Cache
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs
- Validation Architecture for Kernel and Compiler Optimization Agents
More AMD interview questions
- Verifying an RTL Block with a SystemVerilog UVM Testbench Easy
- Debugging Singly Linked-List Insertion and Tracing C++ Method Dispatch Medium
- Single-Agent Versus Multi-Agent Orchestration Architectures Medium Pro
- Constant-Time Fixed-Capacity LRU Cache Medium Pro
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs Medium Pro
- Validation Architecture for Kernel and Compiler Optimization Agents Medium Pro
- Cache-Set Conflicts, False Sharing, and GPU Bank Serialization Medium Pro
- GPU Kernel Register Spilling, Occupancy Trade-Offs, and Performance Diagnosis Medium Pro
- Mastering and Validating Unfamiliar Technologies Medium Pro
- Agent Skill Packaging and Progressive Context Disclosure Medium Pro