O23

Sort Colors (Dutch National Flag)

Junior Level Candidate
Target Time: 15 - 20 Minutes
Type: ARRAY

Problem Statement & Objective

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red (0), white (1), and blue (2). You must solve this problem without using the library's sort function and in a single pass.

Function Signature (Python)

sort_colors(nums: list[int]) -> list[int]

Input & Output Contract

Output Rule:Array sorted in-place [0, ..., 1, ..., 2].

System Constraints

n == nums.length
1 <= n <= 300
nums[i] is either 0, 1, or 2

Example Execution Walkthrough

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

Example Test Scenarios (3)

Example 1: Mixed Array
Input:[[2,0,2,1,1,0]]
Expected Output:[0,0,1,1,2,2]
Example 2: Small Array
Input:[[2,0,1]]
Expected Output:[0,1,2]
Example 3: Single Element
Input:[[0]]
Expected Output:[0]
Loading Python Editor...
Input Parameters
[
  [
    2,
    0,
    2,
    1,
    1,
    0
  ]
]
Expected Output
[
  0,
  0,
  1,
  1,
  2,
  2
]