/75. Sort Colors

75. Sort Colors

Medium
Arrays69.3% acceptance

Given an integer array color_codes 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 sort functions. Return the sorted array.

Example 1

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

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

Explanation: All 0s are first, then 1s, then 2s.

Example 2

Input: [1,0,1,2]

Output: [0,1,1,2]

Explanation: Sorted order of color codes.

Example 3

Input: [2,2,1,0]

Output: [0,1,2,2]

Explanation: Sorted order of color codes.

Constraints

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

Case 1

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

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

Case 2

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

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

Case 3

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

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

Case 4

Input: [2,2,2,2,2]

Expected: [2,2,2,2,2]

Case 5

Input: [0]

Expected: [0]