Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Two Pointers High frequency Solution Available Practice Mode

Sort Colors LeetCode Solution

Tags: #Array #Sorting #Two Pointers

Approach Summary

Dutch National Flag algorithm: three-way partition with lo, mid, hi pointers. Swap to move 0s left, 2s right.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Two Pointers Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Two Pointers pattern.

Framework: Two Pointers • Interview Prep: Tested at FAANG • Explore all Two Pointers problems & invariants →

How to Recognize This Pattern

  • In-place sort of array with only 3 distinct values
  • "Sort 0s, 1s, 2s in one pass"

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Sorting Two Pointers

Frequently Asked Questions

What is the optimal time and space complexity for Sort Colors?
The optimal solution for Sort Colors achieves O(n) runtime complexity and requires O(1) auxiliary space. Each iteration either advances mid or shrinks the hi region, so the loop runs at most n times — O(n) time. Only three index variables, so O(1) space.
How do I identify that Sort Colors requires the Two Pointers pattern?
In technical interviews, look for key problem signals: In-place sort of array with only 3 distinct values; "Sort 0s, 1s, 2s in one pass". Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Two Pointers strategy.
What critical edge cases must be handled in Sort Colors?
Essential edge cases to verify include: All zeros or all twos — the pointer regions still partition correctly; Single element — no swaps needed; Already sorted — the algorithm still makes a full pass; Mixed pattern like 2,0,2,1,1,0 — the mid-not-advancing step after a 2-swap is what makes it correct. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Sort Colors?
Sort Colors is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Microsoft, Amazon.
Buy me a coffee
Daily Practice
0/0