Menu
CoddyTech

Sort Colors

You get an array nums in which every value is 0, 1 or 2. Think of them as three colors, for example red, white and blue. Rearrange the array so that all the 0s come first, then all the 1s, then all the 2s, and return it.

Solve it without a library sort function. The point is to use what you know about the values.

Function

sortColors(nums: integer-array) → integer-array
numsinteger-array
the colors, each one 0, 1 or 2
Returnsinteger-array
the same values with every 0 first, then every 1, then every 2

Constraints

  • 1 ≤ nums.length ≤ 1.5 × 104
  • Every nums[i] is 0, 1 or 2.
  • A color may be missing, and the array may hold a single color.

Examples

Input
nums = [2, 1, 0, 2, 0, 1, 1]
Output
[0, 0, 1, 1, 1, 2, 2]
Explanation
The array holds two 0s, three 1s and two 2s, so the result is exactly that: two 0s, then three 1s, then two 2s.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

What would you change if there were k colors instead of three, with k much smaller than the length of the array?

Reset code
def sortColors(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [2, 1, 0, 2, 0, 1, 1]

Expected

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