Loading practice problems…
Loading your practice workspace…
Loading code editor…
18 / 29
Sign in
Algorithms/Sorting

Sort Colors

medium25 min

Given an array containing only 0, 1, and 2, sort it in place so equal values are adjacent and ordered 0, then 1, then 2.

Return the sorted array. Do not use a built-in sorting function.

Example 1

Inputnums = [2, 0, 2, 1, 1, 0]

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

Example 2

Inputnums = [2, 0, 1]

Output[0, 1, 2]

Constraints

  • 1 ≤ nums.length ≤ 300
  • nums[i] is 0, 1, or 2.
SortingThree Pointers