#75

Sort Colors

Medium Dutch National Flag

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The array contains only 0, 1 and 2. Sort it in place in one pass without using a library sort.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sort 0s, 1s and 2s in one pass, in place.

Why this works: three zones: [0..low) are 0s, [low..mid) are 1s, (high..end] are 2s. Look at nums[mid] and send it to the right zone.

Example: [2, 0, 2, 1, 1, 0]

mid=0 is 2 → swap with high → [0, 0, 2, 1, 1, 2]0 → low, 0 → low, 2 → swap with high → [0, 0, 1, 1, 2, 2]1, 1 → mid moves → done

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Advancing mid after swapping with high, which skips an unchecked element.

Solve on LeetCode ↗
Complexity
  • Time: O(n), one pass.
  • Space: O(1).
Topic: Kadane, Dutch Flag & Moore's Voting
🎬 Episodes 11–13: video coming soon