LeetCode 75, Medium. Topics: Array, Two Pointers, Sorting. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:
Problem
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, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
Examples
Constraints
n == nums.length
1 <= n <= 300
nums[i] is either 0, 1, or 2.
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Grind 75, Grind, NeetCode 250, NeetCode All, AlgoMaster 75. Last modified on September 7, 2026