Skip to main content
mediumGrind 75

Sort Colors

Sort an array containing 0, 1, and 2 in-place 0 = red, 1 = white, 2 = blue Example: [2,0,2,1,1,0] => [0,0,1,1,2,2]

Sort Colors looks brute-forceable, but it's really about moving pointers with a reason. Interviewers love it because it reveals your invariant-driven scanning and your edge-case discipline. The trap is moving the wrong pointer and silently skipping the real answer.

Examples

You write

sort_colors(nums: List[int])

  1. Example 1

    Input
    [2,0,2,1,1,0]
    returns
    [0,0,1,1,2,2]
  2. Example 2

    Input
    [2,0,1]
    returns
    [0,1,2]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Two Pointers

I reach for it when

  • The array is sorted, or you can sort it.
  • You need a pair, a triple or a palindrome.

Say this before you type. Say what each pointer means and what a move to the left or right rules out.

All 26 Two Pointers problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Sort Colorsmedium
2Part 2
3Part 3

Each locked part opens in the editor once the part before it passes.

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.