~/problems / Two pointers

Sort Colors

medium ~25 min

A list holds only the values 0, 1 and 2 (think red, white, blue). Write sort_colors(nums) that rearranges it in place so all 0s come first, then all 1s, then all 2s. It returns None; the caller looks at the mutated list.

  • 1 <= len(nums) <= 10^5.
  • Don't call sort/sorted. Counting the three values and rewriting the list is a valid two-pass answer; the target is one pass with O(1) extra space. (The tests can't check these two rules, so they're up to you.)
a = [2, 0, 1, 2, 0]
sort_colors(a)
a   # [0, 0, 1, 2, 2]
Show hint

keep three regions as you scan: 0s at the front, 2s at the back, and an unexplored middle. Each element you look at can be swapped straight into its region; be careful about what a swap brings back into the part you haven't checked yet.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc