Skip to contentKEEP THE CRAFTTHE SANCTUARY

Quickselect

Find one rank by partitioning and discarding the side that cannot contain it. Keep zero-based target indexes separate from one-based kth input and count duplicates as separate ranked entries.

1 practice exercise4 interview problems

Recognize it when Only the kth value is required, not a complete sorted list.

Checking your account…

Quickselect Code Labs

Partition Toward One Rank

Quickselect uses the same partition operation as quicksort, but only the side containing the target rank remains relevant.

Discard the Side Without the Target

After partition, the pivot has its final rank. If that rank is below target, discard it and the left side; if above, discard it and the right side.

Trace Quickselect Partitions

Reference
def quickselect_trace(values,k):
    values=values.copy();left=0;right=len(values)-1;trace=[]
    while left<=right:
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary];trace.append([left,right,boundary])
        if boundary==k:break
        if boundary<k:left=boundary+1
        else:right=boundary-1
    return trace
Practice

Implement quickselect_trace(values,k). k is zero-based smallest rank; return [left,right,pivot_index] after each partition until found. values must be nonempty and 0 <= k < len(values).

Public tests

  • Discard the side without the rank

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Quickselect Partitions

def quickselect_trace(values,k):
    values=values.copy();left=0;right=len(values)-1;trace=[]
    while left<=right:
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary];trace.append([left,right,boundary])
        if boundary==k:break
        if boundary<k:left=boundary+1
        else:right=boundary-1
    return trace

Shrink Toward One Absolute Target

Predict the actual trace Lab with target index 2. This original input produces a small pivot, then a large pivot, then the desired pivot; the target index never changes because the Lab uses absolute array indexes.

Step Executed statement State Why
Target rank values=values.copy();left=0;right=len(values)-1;trace=[] target k=2, active [0,3] The trace interface already uses a zero-based absolute target.
Pivot 1 values[boundary],values[right]=values[right],values[boundary] values=[1, 2, 5, 6], boundary=0 Only the right side can contain target 2.
Discard left if boundary<k:left=boundary+1 active [1,3] The finalized pivot is excluded.
Pivot 6 else:right=boundary-1 boundary=3, active becomes [1,2] Only the left side can contain target 2.
Pivot 5 if boundary==k:break boundary=2; trace has three partitions The requested rank is now finalized; neither other side needs sorting.
Print Output
print(quickselect_trace([6, 2, 5, 1], 2)) [[0, 3, 0], [1, 3, 3], [1, 2, 2]]

The kth-value Lab translates its one-based input once. A list-group implementation would instead translate k after discarding lower groups; do not mix that different representation with this absolute-index code.

Interpret K and Pivot Rank Carefully

Translate one-based kth-smallest input to zero-based target exactly once. Kth largest can map to n minus k or invert the partition relation; mixing conventions causes off-by-one errors.

Find the Kth Smallest Value

Reference
def kth_smallest(values,k):
    values=values.copy();target=k-1;left=0;right=len(values)-1
    while True:
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary]
        if boundary==target:return values[boundary]
        if boundary<target:left=boundary+1
        else:right=boundary-1
Practice

Implement kth_smallest(values,k). k is one-based; return the kth smallest value without mutating input. values must be nonempty and 1 <= k <= len(values).

Public tests

  • Interpret one-based rank correctly

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find the Kth Smallest Value

def kth_smallest(values,k):
    values=values.copy();target=k-1;left=0;right=len(values)-1
    while True:
        pivot=values[right];boundary=left
        for index in range(left,right):
            if values[index]<=pivot:values[boundary],values[index]=values[index],values[boundary];boundary+=1
        values[boundary],values[right]=values[right],values[boundary]
        if boundary==target:return values[boundary]
        if boundary<target:left=boundary+1
        else:right=boundary-1

Control Randomized Worst Cases

For distinct keys, random pivots yield expected O(n) work because only one shrinking side is processed. The actual two-way at-most-pivot scheme can remain quadratic on all-equal input even with random pivot positions: pivot rank repeatedly lands at an endpoint. A three-way equal band can finish every target within that band immediately. The deterministic Lab also has quadratic adversarial cases; partition selection is not a stable ordering operation.

Explain It in an Interview

Say: “Partition fixes one pivot rank. Only one side can contain target rank k, so I discard the other instead of sorting it.” State input mutation, duplicates, expected and worst-case time, and rank convention.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Randomized quickselectO(n)O(n^2)The expectation requires randomized pivots and distinct keys or duplicate-aware partitioning. The actual last-pivot <= Lab still scans near-full sides on all-equal inputs.

Space

O(n) for the copied input plus O(1) iterative partition state; trace rows add up to O(n).

Assumptions

  • Rank counts duplicate occurrences, not distinct values.
  • Partitioning each near-full range under extreme pivots causes quadratic total scanning.

Invariants Worth Saying Aloud

  1. The target absolute index remains inside the active range.
  2. A partition pivot is at its final sorted rank, with <= values before it and > values after it.
  3. Only the strict side containing target remains active.

When To Use Or Avoid Quickselect

Use It When

  • Use randomized quickselect for expected linear selection on distinct keys, or use duplicate-aware three-way partitioning when multiplicities are large.
  • Use a heap for streaming top-k or maintained sorted for a simpler small-input answer.

Choose Another Tool When

  • The deterministic last-pivot Lab can take quadratic work on ordered or duplicate-heavy input.
  • A selected value does not imply the remaining array is globally sorted.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using a one-based rank as an array index

Rank 1 means the first value at zero-based index 0, not index 1.

Prevent it: Translate once at the interface: target = k - 1.

Avoid

target = k

Use instead

target = k - 1

Selecting distinct values instead of occurrences

[2,2,5] has second-smallest value 2. Removing duplicates changes the rank contract.

Prevent it: Retain multiplicities throughout partitioning.

Avoid

answer = sorted(set(values))[k - 1]

Use instead

answer = sorted(values)[k - 1]

Retaining the finalized pivot in a discarded side

If pivot index 0 is below target, left = pivot can repeat the same range.

Prevent it: Start the right side strictly after the pivot.

Avoid

left = pivot_index

Use instead

left = pivot_index + 1

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.