Partition a List Around a Pivot

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
Write partition_around(items, pivot) that rearranges items (in place, returning it too) so that every element less than pivot comes before every element greater than or equal to pivot. The relative order within each partition does not need to be preserved. Use an in-place two-pointer swap approach (like the Lomuto partition scheme), not sorted().

Examples

Example 1
Input
items = [9, 3, 7, 1, 8, 2], pivot = 5
Output
[3, 1, 2, 9, 8, 7]
Explanation

Every value less than 5 (3, 1, 2) ends up before every value 5 or greater (9, 8, 7); exact internal order can vary by implementation but this traces the given solution's swaps.

Constraints

  • 0 <= len(items) <= 10^4

Topics

ListsTwo Pointers

Companies

GoogleUber

Hints

Hint 1

Keep a boundary index marking the end of the "less than pivot" section; scan and swap elements smaller than pivot into that section.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.