Partition Array According to Given Pivot (LeetCode 2161): Solution and Explanation
Rearrange an array into three groups: values below the pivot, values equal to it, and values above it. Unlike quicksort partitioning, each group must keep the order it had in the input.
Intuition
In-place partition schemes such as Lomuto or Hoare swap elements across the array and scramble their order. The stability rule rules them out, so build the answer in a new array.
Values smaller than the pivot fill the result from the left, in the order you meet them when scanning nums from the left. That keeps their order for free.
Values larger than the pivot can fill the result from the right if you scan nums from the right: the last larger value lands in the last slot, the one before it just left of that, and so on. Pre-filling the result with the pivot means the slots that neither side writes already hold the right value.
Approach: Pivot-filled result with front and back writers
- Create
resultof length n filled withpivot. - Set
lo = 0andhi = n - 1. - For i from 0 to n - 1: if
nums[i] < pivot, write it toresult[lo]and incrementlo. - In the same iteration, if
nums[n - 1 - i] > pivot, write it toresult[hi]and decrementhi. - Return
result. The slots fromlotohiwere never written and hold the pivot copies.
Step-by-step example
nums = [9,12,5,10,14,3,10], pivot = 10
- result starts as [10,10,10,10,10,10,10], lo = 0, hi = 6.
- i = 0: 9 < 10 goes to result[0]. The back reader sees nums[6] = 10, not larger, so nothing.
- i = 1: 12 is not smaller. The back reader sees nums[5] = 3, not larger. i = 2: 5 goes to result[1]; nums[4] = 14 goes to result[6].
- i = 3: the pivot 10 is skipped by both. i = 4: nums[2] = 5 is not larger. i = 5: 3 goes to result[2]; nums[1] = 12 goes to result[5].
- i = 6 changes nothing. Slots 3 and 4 still hold 10, giving [9,5,3,10,10,12,14].
Code: Python, Java, C++
1class Solution:
2 def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
3 n = len(nums)
4 result = [pivot] * n
5 lo, hi = 0, n - 1
6 for i in range(n):
7 if nums[i] < pivot:
8 result[lo] = nums[i]
9 lo += 1
10 if nums[n - 1 - i] > pivot:
11 result[hi] = nums[n - 1 - i]
12 hi -= 1
13 return result1class Solution {
2 public int[] pivotArray(int[] nums, int pivot) {
3 int n = nums.length;
4 int[] result = new int[n];
5 Arrays.fill(result, pivot);
6 int lo = 0, hi = n - 1;
7 for (int i = 0; i < n; i++) {
8 if (nums[i] < pivot) {
9 result[lo++] = nums[i];
10 }
11 if (nums[n - 1 - i] > pivot) {
12 result[hi--] = nums[n - 1 - i];
13 }
14 }
15 return result;
16 }
17}1class Solution {
2public:
3 vector<int> pivotArray(vector<int>& nums, int pivot) {
4 int n = nums.size();
5 vector<int> result(n, pivot);
6 int lo = 0, hi = n - 1;
7 for (int i = 0; i < n; i++) {
8 if (nums[i] < pivot) {
9 result[lo++] = nums[i];
10 }
11 if (nums[n - 1 - i] > pivot) {
12 result[hi--] = nums[n - 1 - i];
13 }
14 }
15 return result;
16 }
17};Time and space complexity
O(n)
One loop of n iterations, each doing two comparisons and at most two writes.
O(n)
The result array. No other storage grows with n.
Other approaches
Three lists (time O(n), space O(n))
Collect the smaller, equal and larger values into three lists in one scan and concatenate them. It is the most obvious stable solution with the same complexity, but it allocates three extra lists.
Count, then three write pointers (time O(n), space O(n))
Count how many values are smaller and equal first, then place each value at the next free slot of its group in a second pass. It uses two passes but no pre-fill trick.
Stable sort by group (time O(n log n), space O(n))
Sort by the key -1, 0 or 1 for smaller, equal, larger with a stable sort. Short to write, but O(n log n).
Common mistakes
- Using an in-place swap partition, which breaks the relative order inside a group.
- Writing larger values from the back while scanning from the front, which reverses their order.
- Forgetting the pivot copies. Pre-fill with pivot or count them and fill the middle at the end.
- Assuming the pivot appears only once. Several elements may equal it.
Frequently asked questions
Why does scanning from the back keep the larger values in order?
The back reader meets the larger values from last to first and writes them from the last slot leftward. The last one ends up rightmost, so the original order is preserved.
Could this be done in O(1) extra space?
Stable partitioning in place is possible with rotations, but it costs O(n log n) time or more. Since the answer is a new array anyway, O(n) space is the practical choice.
How is this related to Sort Colors?
Sort Colors is also a three-way partition, but it has only three distinct values, so order inside a group does not matter and the Dutch national flag swaps work in place.