Sort Colors
LeetCode 75 · Medium · solution, intuition & step-by-step walkthrough
low / mid / high pointers partition into 0s, 1s, 2s in one pass.
This is how I solved Sort Colors (LeetCode 75), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
Approach
- 1
0 at mid: swap with low, advance both.
- 2
1 at mid: just advance mid.
- 3
2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
How I solved it
Dutch national flagPythonO(n) time · O(1) space
class Solution:
def sortColors(self, nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
low=0
mid = 0
high = len(nums)-1
while mid<=high:
if nums[mid]==0:
#move left
nums[low],nums[mid]=nums[mid],nums[low]
#increase right boundary of 0
low+=1
mid+=1
elif nums[mid]==1:
#no worries
mid+=1
elif nums[mid]==2:
nums[mid],nums[high]=nums[high],nums[mid]
#increase the left boundary of 2
high-=1
Sort Colors — FAQ
What is the intuition behind Sort Colors?
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
How do you solve Sort Colors (LeetCode 75)?
1. 0 at mid: swap with low, advance both. 2. 1 at mid: just advance mid. 3. 2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
What is the time and space complexity of Sort Colors?
Time: O(n). Space: O(1). (Accepted approach: Dutch national flag.)
What are common mistakes in Sort Colors?
Don't increment mid after swapping with high.