Sort Colors
Dutch National Flag — partition into 3 groups with one pass.
Problem Statement
Given an array nums containing only 0, 1, and 2, sort it in-place so that objects of the same color are adjacent (0s, then 1s, then 2s). Do not use the library sort function.
Examples
Example 1
Example 2
Constraints
- n == nums.length
- 1 ≤ n ≤ 300
- nums[i] is 0, 1, or 2.
Solutions
Count occurrences of 0, 1, 2. Then overwrite the array with the correct count of each. Simple and O(n) but requires two passes.
Related Concepts
Deepen your understanding with these related topics from our AI Glossary:
Want to master the core concepts?
Our free AI Glossary covers 190+ topics — from Dutch National Flag to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.
Stuck? Ask AI to explain it step by step.
Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.
Free to start · No credit card required to explore
Get Started Free