AlgoFrames

Sort colors (Dutch national flag)

Challenge · Write code · about 20 min

The array nums holds only 0, 1 and 2 (red, white, blue). Sort it in place in one pass so all 0s come first, then all 1s, then all 2s. Do not use a library sort.

Return the same array.

Example 1

Input:

[[2,0,2,1,1,0]]

Output:

[0,0,1,1,2,2]

Example 2

Input:

[[2,0,1]]

Output:

[0,1,2]

Constraints

  • 0 ≤ nums.length ≤ 1,000
  • nums[i] is 0, 1 or 2
  • One pass and O(1) extra space

Learn the idea first: Quick sort: partitioning and pivots, a visual lesson.

More Quick sort: partitioning and pivots problems