MediumArraysTwo PointersSorting

2 approaches, code in every language

Problem description

You are given an array whose entries are only the integers 0, 1, and 2, where each value stands for a color: red, white, and blue respectively. Rearrange the array in place so that every 0 comes first, then every 1, and finally every 2, keeping identical colors grouped together.

Solve it without leaning on a library sorting routine, and ideally in a single pass over the data using constant extra space.

Example 1

Input: nums = [2,0,2,1,1,0]

Output: [0,0,1,1,2,2]

All the reds move to the front, the whites to the middle, and the blues to the end.

Example 2

Input: nums = [2,0,1]

Output: [0,1,2]

Constraints

  • 1 ≤ nums.length ≤ 300
  • nums[i] is one of 0, 1, or 2

After the pattern

Now solve one you haven't seen.

Triage Band Ordering is our own problem on the technique behind Sort Colors: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free