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 k copies of it so the returned list always has length k.
  • Boundary counts: When k == 0, return []. When k == len(values), return every element of values ordered from largest to smallest.
  • Partition-first selection: Isolate the k largest occurrences via Quickselect-style partitioning so the unselected len(values) - k items never need to be sorted against one another, then sort only the k chosen items for an expected O(n + k log k) runtime.
  • Memory & trade-offs: You may partition values directly or copy it first if you account for the O(n) extra space. Be ready to discuss pivot strategy, duplicate-heavy inputs, worst-case quadratic behavior in naive Quickselect, and when an O(n log k) min-heap or O(n log n) full sort is preferable (such as unbounded streams or very small k).

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,000
  • 0 <= k <= len(values)
  • -2^31 <= values[i] <= 2^31 - 1

Step-by-step walkthrough

  1. Separate selection from sorting

    We are given a list values of length n (0 <= n <= 200,000) and an integer k (0 <= k <= n), and we want the k largest occurrences returned in descending order:

    • Duplicates count separately: [5, 12, 4, 12, 8, 2] with k = 3 returns [12, 12, 8], keeping both 12s.
    • Boundary cases: k = 0 returns []; k = n returns all n numbers sorted descending.

    The central insight is that this task splits into two independent jobs:

    1. Selection: find the cutoff between the k largest occurrences and the n - k smaller ones, placing those k winners into arr[:k] in any order.
    2. Output sorting: sort only those k winners descending (O(k log k)).

    Nothing in the problem asks us to order the n - k discarded elements against each other.

  2. Compare full sort, min-heap, and quickselect

    Before coding, let's compare the three standard ways to get the top k elements 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]) does O(n log n) work even when k = 5, spending almost all its effort sorting n - k losers.
    • Min-heap of size k keeps the k largest elements seen so far, with the smallest of those k sitting at the root. Each incoming element either skips the heap in O(1) or replaces the root in O(log k). That gives O(n log k) time and O(k) memory, and works in a single streaming pass — ideal when k is tiny or data does not fit in memory, though when k grows close to n, O(n log k) approaches O(n log n).
    • Partition-based selection (quickselect) finds the k winners in expected O(n) time by repeatedly partitioning only the subarray that contains index k - 1, then sorts just arr[:k] in O(k log k).
  3. Key idea: three-way partitioning around a random pivot

    Suppose we pick a pivot value inside our active subarray arr[lo..hi] and rearrange arr[lo..hi] into three contiguous blocks:

    [  strictly > pivot  |    == pivot    |  strictly < pivot  ]
      lo .. eq_start-1     eq_start..eq_end-1   eq_end .. hi
    

    Where does the last selected slot target_idx = k - 1 land?

    1. Inside > pivot (target_idx < eq_start): There are already more than k elements larger than pivot, so we throw away the == pivot and < pivot blocks (hi = eq_start - 1).
    2. Inside == pivot (eq_start <= target_idx < eq_end): Every slot before k is >= pivot and every slot from k onward is <= pivot. arr[:k] already holds the exact k largest occurrences — we stop!
    3. Inside < pivot (target_idx >= eq_end): Everything in > pivot and == pivot definitely belongs in the top k, 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 picking arr[lo] degrades to O(n^2) on sorted or reverse-sorted arrays because each round trims only 1 element. A random pivot lands in the middle half of the window with probability 1/2, shrinking the window geometrically for O(n) expected total work (while still having a theoretical O(n^2) worst case if random draws are maximally unlucky every round).
    • Three-way partition instead of two-way: If all 50,000 elements equal 7, a naive two-way partition pushes 49,999 copies to one side and takes quadratic time. Three-way partitioning groups all 50,000 copies into == pivot and finishes in one single pass.
  4. Code the Dutch National Flag partition

    To partition arr[lo..hi] into > pivot, == pivot, and < pivot in one pass with O(1) extra variables, we maintain three pointers (gt_end, i, lt_start) dividing arr[lo..hi] into four zones:

      lo          gt_end          i             lt_start          hi
      |  > pivot  |   == pivot    |   unseen    |     < pivot     |
    

    As i scans across the unseen zone (while i <= lt_start:):

    • arr[i] > pivot: Swap arr[gt_end] and arr[i], then increment both gt_end and i. Why is advancing i safe here? Because arr[gt_end] came from the == pivot zone (or gt_end == i), so we already know what swapped into arr[i].
    • arr[i] < pivot: Swap arr[i] and arr[lt_start], and decrement lt_start — without advancing i! Why keep i still? Because the number swapped in from arr[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 advance i to grow the == pivot zone.
    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
    
  5. Code the quickselect loop and k-element sort

    Now we wrap _partition_three_way inside largest_k:

    1. Handle k <= 0 immediately (return []), since target_idx = k - 1 only exists when k >= 1.
    2. Copy values into arr = list(values) so the caller's list is never scrambled (O(n) extra space; if an interviewer asks for O(1) auxiliary space, partition values directly).
    3. Narrow [lo, hi] around target_idx = k - 1 until eq_start <= target_idx < eq_end. Notice how ties across index k - 1 resolve effortlessly: if three 4s span indices 2, 3, 4 and k = 4 (target_idx = 3), arr[:4] takes two of the 4s and leaves the third behind.
    4. Slice selected = arr[:k] and sort only those k items 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
    
  6. Trace Example 1 step by step

    Let's trace values = [5, 12, 4, 12, 8, 2] with k = 3, so target_idx = k - 1 = 2, lo = 0, hi = 5. Suppose random.randint(0, 5) picks index 4, giving pivot = 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=3
    

    Now we check where target_idx = 2 sits:

    • eq_start = 2 <= target_idx = 2 < eq_end = 3, so target_idx landed inside the == 8 block!
    • Selection stops immediately. arr[:3] is [12, 12, 8].
    • Sorting only those 3 items descending yields [12, 12, 8], while the unselected tail [4, 2, 5] at indices 3..5 is left completely unsorted.
  7. 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-case O(n^2). Each call to _partition_three_way scans arr[lo..hi] once in time proportional to the current window length. Because a random pivot lands in the middle half of the window with probability 1/2, the window shrinks by a constant factor (at least 3/4 on average every two rounds), so expected selection work is a geometric series n + (3/4)n + (3/4)^2 n + ... = O(n). Afterward, sorting arr[:k] takes O(k log k). In the astronomically unlikely worst case where random pivots repeatedly pick the extreme element every round, selection takes O(n^2) (no fixed input pattern — sorted, reversed, or all-equal — can force this).
  • Space: O(n) extra to copy values, plus O(k) for the returned list. Copying arr = list(values) preserves the caller's input list, and our iterative while loop uses O(1) pointer variables with zero recursion stack. If mutating values in place is allowed, auxiliary selection space drops to O(1).

Edge cases

  • k == 0 (including values = []): Returns [] immediately before computing target_idx = k - 1 = -1.
  • k == len(values): target_idx = n - 1 selects all n items, 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 of 4 straddle index k - 1 = 3, the == 4 zone covers index 3 and arr[:4] cleanly keeps [9, 7, 4, 4].
  • All elements equal (50,000 copies of 7): Three-way partitioning puts all 50,000 items into == pivot (eq_start = 0, eq_end = 50000) and exits on the very first round in O(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^31 and 2^31 - 1): Only < and > comparisons are performed (never arithmetic like a - 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 i after swapping arr[i] with arr[lt_start]: The element swapped in from lt_start has not been compared against pivot yet; incrementing i skips it and corrupts the partition.
  • Using a deterministic pivot (arr[lo] or arr[hi]): Adversarially ordered or already-sorted inputs trigger O(n^2) behavior deterministically.
  • Using two-way Lomuto partitioning on duplicate-heavy inputs: Sending all == pivot values to one side causes O(n^2) runtime when most values are identical.
  • Off-by-one on the boundary index: k items occupy indices 0 .. k - 1, so the boundary slot is k - 1, not k.
  • Sorting all of arr at the end instead of arr[:k]: Calling arr.sort(reverse=True) throws away the O(n) selection win and reverts total runtime to O(n log n).

Alternative approaches

  • Min-heap of size k (heapq.nlargest): Maintain a min-heap holding the k largest values seen so far; for each new x, if x > heap[0], replace the root in O(log k). This runs in O(n log k) time and O(k) memory without copying or modifying values, making it superior when k is very small (k << n) or when values arrive as an unbounded stream.
  • Full sort (sorted(values, reverse=True)[:k]): Takes O(n log n) time and O(n) space. In Python, Timsort runs in fast C code, so for modest n or when k is close to n (k log k ≈ n log n) it is competitive in wall-clock time, though asymptotically slower when k << 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-case O(n) time (with a high constant factor). Introselect (used by C++ std::nth_element and numpy.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 values arrives as a stream that cannot fit in RAM, whenever callers forbid both mutating and copying an O(n) array (O(k) heap memory vs O(n) copy), or when k is tiny (say k = 10 out of 10^7 items, where one sequential read pass with O(log 10) register-cache heap ops beats random-access array writes). Choose quickselect when the data already lives in memory and k can be moderate or large (k = 50,000), where O(n + k log k) avoids n heap operations of cost O(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 into 5s, taking each group's median, and selecting the median of those medians as the pivot) only if random draws stall. That guarantees O(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_k or a size-k min-heap) on its shard to emit at most k local winners in descending order, then send those M sorted lists (at most M * k numbers total) to a coordinator that merges them with a k-step k-way merge (or another largest_k call). This is exact because no item outside a shard's local top k can ever place in the global top k.

Follow-up questions

Similar questions

More AMD interview questions

All 19 AMD questions →