Skip to content
Decoder

Sort Colors

Medium

Problem

A list nums holds only the values 0, 1 and 2 (think red, white and blue). Sort it in place so that all 0s come first, then all 1s, then all 2s. Do not use a library sort. As a follow-up, do it in one pass with O(1) extra space.

Example 1

Input
nums = [2, 0, 2, 1, 1, 0]
Output
nums becomes [0, 0, 1, 1, 2, 2]

Example 2

Input
nums = [2, 0, 1]
Output
nums becomes [0, 1, 2]

The function returns nothing; the tests inspect nums after the call.

Constraints

  • 1 <= nums.length <= 300
  • nums[i] is 0, 1 or 2.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.