Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

Sort three colours in one pass

Medium · Target 15 minutes · Two pointers

An array nums holds only the values 0, 1 and 2. Sort it in place in a single pass, using O(1) extra memory and no library sort, and return it.

Examples

InputOutputWhy
nums = [2, 0, 2, 1, 1, 0][0, 0, 1, 1, 2, 2]
nums = [2, 0, 1][0, 1, 2]

Constraints

  • 1 ≤ n ≤ 300
  • nums[i] is 0, 1 or 2

Hints

Hint 1

Counting the 0s, 1s and 2s and rewriting the array takes two passes. Can one pass place each value as it is read?

Hint 2

Keep the zeros at the front and the twos at the back as you go. What regions does the array have part-way through?

Hint 3

Use lo, mid and hi: [0, lo) holds 0s, [lo, mid) holds 1s, (hi, n) holds 2s, and [mid, hi] is unread. Look at nums[mid] and decide.

Where people lose marks

  • Advancing mid after swapping a 2 to the back: the value swapped in from hi has not been examined and may be a 0 or a 2.
  • Looping while mid < hi instead of mid ≤ hi, which leaves the last unread element unexamined.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.