75. Sort Colors
Asked at 37Microsoft65Amazon62Bloomberg61Meta57Google54Apple35tcs73Walmart Labs71Agoda69Pocket Gems100Slice100Target100Autodesk69Nagarro67Morgan Stanley64eBay64Info Edge63HashedIn62Swiggy59Adobe55Visa55ServiceNow55Nvidia55Samsung53Oracle52Capgemini52TikTok46IBM44Flipkart43PayPal42Salesforce41Snowflake39Cisco37Capital One35Goldman Sachs33Infosys30Uber22
Problem
nums holds only 0s, 1s and 2s (red, white, blue). Sort it in place so all 0s come first, then 1s, then 2s, without a library sort.
Example: [2,0,2,1,1,0] → [0,0,1,1,2,2]
Constraints: follow-up: one pass with O(1) extra space.
Dutch national flag: lo = next slot for 0, hi = next slot for 2, i scans. Swap 0s to the front, 2s to the back (don't advance i after swapping with hi, since the swapped-in value is unexamined).
[2 0 2 1 1 0]
lo/i hi 2 -> swap with hi, hi--
...
result [0 0 1 1 2 2] regions: [0..lo) = 0, [lo..i) = 1, (hi..] = 2
Complexity: O(n) one pass, O(1) space.
class Solution:
def sortColors(self, nums: List[int]) -> None:
lo, i, hi = 0, 0, len(nums) - 1
while i <= hi:
if nums[i] == 0:
nums[lo], nums[i] = nums[i], nums[lo]
lo += 1; i += 1
elif nums[i] == 2:
nums[hi], nums[i] = nums[i], nums[hi]
hi -= 1
else:
i += 1
a = [2, 0, 2, 1, 1, 0]; Solution().sortColors(a)
assert a == [0, 0, 1, 1, 2, 2]
a = [2, 0, 1]; Solution().sortColors(a)
assert a == [0, 1, 2]
a = [1, 1, 0, 0, 2, 2, 1]; Solution().sortColors(a)
assert a == [0, 0, 1, 1, 1, 2, 2]
class Solution {
public void sortColors(int[] nums) {
int lo = 0, i = 0, hi = nums.length - 1;
while (i <= hi) {
if (nums[i] == 0) swap(nums, lo++, i++);
else if (nums[i] == 2) swap(nums, i, hi--);
else i++;
}
}
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
func sortColors(nums []int) {
lo, i, hi := 0, 0, len(nums)-1 // [0,lo) = 0s, [lo,i) = 1s, (hi,end] = 2s
for i <= hi {
switch nums[i] {
case 0:
nums[lo], nums[i] = nums[i], nums[lo]
lo++
i++
case 2:
nums[hi], nums[i] = nums[i], nums[hi]
hi--
default:
i++
}
}
}