Three way partitioning of an array around a given value
Pattern: Dutch national flag
Sort Colors with ranges instead of colours. Values below a go to the front, values above b go to the back, and values in between stay in the middle, all in one pass.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given an array of whole numbers and a range [a, b] with a ≤ b. Rearrange the array in place so that all
values smaller than a come first, then all values from a to b, then all values larger than b. The order inside
each group does not matter. For example, [9, 15, 2, 30, 18, 1] with [10, 20] can become [9, 2, 1, 15, 18, 30].
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
threeWayPartition is this guide's own. Since any order inside a group is correct, this guide's tests check the group
rule and the values, not one exact arrangement.
Think first
- How is this the same as Sort Colors?
- Which of the three groups does a value belong to? What replaces "0", "1" and "2"?
- After swapping with
high, why must the new value be checked?
Hints
Brute force, and why it fails
Sorting the array also satisfies the rule, in O(n log n). Copying the three groups into a new array is O(n) time but O(n) memory. The three-pointer pass is O(n) time and O(1) memory.
The key insight
The Dutch national flag method only needs to know which of three groups a value belongs to. Two comparisons with a
and b give that, so the same one-pass partition works.
Dry run
arr = [9, 15, 2, 30, 18, 1] with a = 10 and b = 20. Below 10 goes first, 10 to 20 in the middle, above 20 last.
The plan
low = 0, mid = 0, high = n - 1
while mid <= high:
if arr[mid] < a:
swap arr[low], arr[mid]; low = low + 1; mid = mid + 1
else if arr[mid] > b:
swap arr[mid], arr[high]; high = high - 1
else:
mid = mid + 1
Complexity
- Time
O(n)- Space
O(1)
Each step shrinks the unknown region by one.
Edge cases
- Every value in one group: nothing really moves.
a = b: the middle group holds only copies of that value.- No value in range, as in
[9, 8, 1, 0]with[2, 5]: two groups only.
I've built my logic, show the code
Java
class Solution {
public void threeWayPartition(int[] arr, int a, int b) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
if (arr[mid] < a) {
swap(arr, low++, mid++); // belongs to the first group
} else if (arr[mid] > b) {
swap(arr, mid, high--); // belongs to the last group; check the swapped-in value next
} else {
mid++; // inside [a, b]: already in the middle group
}
}
}
private void swap(int[] x, int i, int j) {
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}C++
class Solution {
public:
void threeWayPartition(vector<int>& arr, int a, int b) {
int low = 0, mid = 0, high = static_cast<int>(arr.size()) - 1;
while (mid <= high) {
if (arr[mid] < a) {
swap(arr[low++], arr[mid++]); // belongs to the first group
} else if (arr[mid] > b) {
swap(arr[mid], arr[high--]); // belongs to the last group; check the swapped-in value next
} else {
mid++; // inside [a, b]: already in the middle group
}
}
}
};Python
class Solution:
def threeWayPartition(self, arr: list[int], a: int, b: int) -> None:
low = mid = 0
high = len(arr) - 1
while mid <= high:
if arr[mid] < a:
arr[low], arr[mid] = arr[mid], arr[low] # belongs to the first group
low += 1
mid += 1
elif arr[mid] > b:
arr[mid], arr[high] = arr[high], arr[mid] # belongs to the last group; check it next
high -= 1
else:
mid += 1 # inside [a, b]: already in the middle groupCommon mistakes
- Using
<=againstaor>=againstb, which putsaorbthemselves in the wrong group. - Moving
midafter swapping withhigh. - Expecting one exact output order. Any order inside each group is correct.