Skip to content
CodeShare
All problems

Sort Colors

Sort an array of 0s, 1s and 2s in a single pass.

MediumArraysTwo pointersSorting

The array nums holds objects colored red, white or blue, written as 0, 1 and 2. Sort them in place so that objects of the same color are together, in the order red, white, blue.

Don't use the library's sort. The tests check nums after your function finishes. Can you do it in one pass?

Examples

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

Constraints

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