Skip to content
Problem 75 · LeetCode 75(opens in a new tab)

Sort Colors

MediumArrays

An array nums holds n items, each painted one of three colours: 0 for red, 1 for white and 2 for blue.

Rearrange the array in place so all the 0s come first, then all the 1s, then all the 2s. Do not call a library sort. The function returns nothing; only the array changes.

Example 1

Input:  nums = [2, 0, 1, 2, 1, 2]
Output: [0, 1, 1, 2, 2, 2]
Why:    one 0, two 1s and three 2s, grouped in order
2 more examples and the constraints

Example 2

Input:  nums = [2, 1, 0]
Output: [0, 1, 2]
Why:    the order is simply reversed

Example 3

Input:  nums = [1]
Output: [1]
Why:    one item is already sorted

Constraints

  • 1 ≤ n ≤ 300
  • Each nums[i] is 0, 1 or 2
  • Follow-up: one pass, O(1) extra space

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count, then rewriteO(n)
  2. Three pointers, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 300 itemsVerdict
Count, then rewriteO(n)
Passes; two passes
Three pointers, one passO(n)
Best; answers the follow-up

n = number of items. Both are linear; the second reads each item once.

Edge cases to test

  • One item. [1] is already sorted; low, mid and high all start on it.
  • A colour is missing. [2, 0, 2, 0] has no 1s; the middle zone just stays empty.
  • All the same colour. [2, 2, 2] swaps each 2 with itself as high walks back.
  • 2s at the front. [2, 2, 0, 1, 0] swaps a 2 in from the back, so mid must re-read the same cell.

Common mistakes

  • Moving mid forward after swapping with high, which skips an unread value.
  • Looping while mid < high instead of mid ≤ high, which leaves the last cell unread.
  • Returning a new sorted array instead of changing nums in place.

How to talk through it

  1. 1Clarify. In place? No library sort? Can a colour be missing?
  2. 2Give the counting answer. Three values means count them and rewrite: O(n), O(1) space, two passes.
  3. 3Name the zones. 0s before low, 1s up to mid, unread up to high, 2s after. Each step shrinks the unread zone.
  4. 4Code the one pass. Swap 0s to low, skip 1s, swap 2s to high, and explain why mid stays after the last case.
  5. 5Test out loud. Run a single item, a missing colour and 2s at the front before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?