Sort Colors

Medium Two Pointers AI round

nums is a list of numbers, each of them 0, 1 or 2: three colours, one number each.

Put the list in order: all the 0s first, then all the 1s, then all the 2s.

Change nums in place, so that it holds the list in order when your function ends. Return nothing.

Example 1

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

The list holds two 0s, three 1s and two 2s, so in order it is the two 0s, then the three 1s, then the two 2s.

Example 2

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

Example 3

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

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁵
  • nums[i] is 0, 1 or 2

Watch the explanation

More Two Pointers

All Two Pointers problems