Skip to main content

Sort an Array of 0s, 1s and 2s

EasyArraysTwo pointersSorting203 tests

You get an array nums. Every value in it is 0, 1 or 2.

Return the array sorted from smallest to largest: all 0s first, then all 1s, then all 2s.

Do not use a built-in sort. Try to do it in one pass over the array, using O(1) extra space. You may change nums and return it.

Hint

Keep three markers: where the next 0 should go, where the next 2 should go, and the element you are looking at now.

Examples

Example 1

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

There are two 0s, two 1s and one 2. Put them in that order.

Example 2

Input:
[1]
Output:
[1]

An array with one element is already sorted.

Example 3

Input:
[2,2,0]
Output:
[0,2,2]

There are no 1s. The single 0 goes first.

Constraints

  • 1 <= nums.length <= 25
  • nums[i] is 0, 1 or 2.

Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.