/75. Sort Colors

75. Sort Colors

Medium
Arrays69.3% acceptance

Given an integer array color_array of length n, where each element is either 0, 1, or 2, sort the array in-place so that all 0s appear first, followed by all 1s, then all 2s. Do not use built-in sorting functions. The sorting must be performed in-place.

Example 1

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

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

Explanation: All 0s are moved to the front, followed by 1s, then 2s.

Example 2

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

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

Explanation: All 0s are moved to the front, followed by 1s, then 2s.

Constraints

  • 1 <= len(color_array) <= 300
  • Each element in color_array is 0, 1, or 2
Python (current runtime)

Case 1

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

Expected: [0,0,1,1,2,2]

Case 2

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

Expected: [0,0,1,1,2,2]

Case 3

Input: [2,1,0]

Expected: [0,1,2]

Case 4

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

Expected: [0,0,1,1,2,2]

Case 5

Input: [0]

Expected: [0]