Sort Colors

35 min · sortColors()

Three paint colors have spilled into one row of cans. Each can is labeled 0, 1, or 2, and you need the labels grouped in that order.

Given an integer array nums containing only 0, 1, and 2, return the array sorted with every 0 first, then every 1, then every 2.

Think of 0 as red, 1 as white, and 2 as blue. The names add a story; the numeric order decides the result.

A few ground rules:

  • Keep every value exactly once; only its position may change.
  • Return an array with the same length as the input.
  • The intended solution groups all three colors in one scan with constant extra space.

Constraints

  • 1 <= nums.length <= 100_000
  • nums[i] ∈ {0, 1, 2}

Hints

Count before you rearrange

Since there are only three possible values, you can count each one and overwrite the array with the right number of zeroes, ones, and twos.

Split the row into four regions

Track a finished 0 region on the left, an unknown region in the middle, and a finished 2 region on the right. Values between the left boundary and your scanner are the finished 1 region.

A swapped-in value is still unknown

When the scanner finds 2, swap it with the right boundary and shrink that boundary. Don't advance the scanner yet: the value arriving from the right hasn't been classified.

Follow-up

Can you finish in one pass without calling a general-purpose sorting routine?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  0,
  2,
  1,
  1,
  0
]
Expected
[
  0,
  0,
  1,
  1,
  2,
  2
]
Why
equal colors group together in 0, 1, 2 order

Example 2

ready
Input
nums = [
  2,
  2,
  2
]
Expected
[
  2,
  2,
  2
]
Why
a single-color row is already grouped

Example 3

ready
Input
nums = [
  2,
  0,
  1
]
Expected
[
  0,
  1,
  2
]
Why
one of each color lands in numeric order

Interview signal

Asked at

MicrosoftAmazonMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite