noodleProblems/
Sort Colors
#20

Sort Colors

AlgorithmmediumArrayTwo PointersSorting

Given an array nums of n integers that are 0, 1, or 2 — representing the colors red, white, and blue — sort it **in place** so that equal colors are adjacent and ordered 0, 1, 2.

You must mutate the input array directly and return that same array (do not allocate and return a new one). The classic constraint is to do it in one pass with constant extra space, without a library sort.

Example cases

  • mixed
    in nums = [2,0,2,1,1,0]
    out [0,0,1,1,2,2]
    Two of each color, grouped in order.
  • small
    in nums = [2,0,1]
    out [0,1,2]
  • single
    in nums = [0]
    out [0]

Constraints

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