Sort Colors

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array nums with n objects colored red (0), white (1), or blue (2), sort them in-place so that objects of the same color are adjacent, in the order red, white, and blue.

You must solve this problem without using the library's sort function.

Examples

Example 1:

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

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

Explanation: The array is sorted so that all 0s (red) come first, then all 1s (white), then all 2s (blue).

Example 2:

Input: nums = [2, 0, 1]

Output: [0, 1, 2]

Explanation: Each color appears once; sorting yields [0, 1, 2].

Example 3:

Input: nums = [0]

Output: [0]

Explanation: A single-element array is already sorted.

Constraints

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle