Skip to content

Sort Colors

MediumArrays & Hashing
Decode it first. Clues, constraints, pattern and plan before any code.

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.

nums = [2, 0, 2, 1, 1, 0]   →  nums becomes [0, 0, 1, 1, 2, 2]
nums = [2, 0, 1]            →  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.