Given an array that only contains 0s and 1s, rearrange it in place so all the 0s come before all the 1s, in a single pass.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array that only contains 0s and 1s, rearrange it in place so all the 0s come before all the 1s, in a single pass.
A minimal, two-value warm-up for the Dutch National Flag idea — converging boundary pointers that swap elements into place — before Sort Colors adds a third value and a genuinely trickier middle pointer.
Whenever an array holds only a small, fixed set of distinct values and needs to be grouped in place, consider boundary pointers that close in from both ends and swap misplaced elements, rather than counting values and rewriting the array from scratch.
Keep a left pointer starting at index 0 and a right pointer starting at the last index. Advance left forward as long as it points at a 0 (it's already correctly placed), and advance right backward as long as it points at a 1 (also already correct). Once left is stuck on a 1 and right is stuck on a 0, those two elements are both misplaced relative to each other, so swapping them fixes both at once. Repeat until left and right cross — at that point every element before left is a 0 and every element from left onward is a 1.
class Solution {
public void segregate(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] == 0) {
left++;
} else if (nums[right] == 1) {
right--;
} else {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
}
}