Two Pointers pattern

Sort Colors

Given an array of objects colored 0, 1, or 2, sort them in place so equal colors are grouped in that order, ideally in a single pass. Watch it run step by step, then write your own pseudocode and get it checked by AI.

  • LeetCode 75
  • Medium
  • 3 approaches

Sign in with Google or GitHub and you land straight on this page. DSA comes with the all labs plan and every ChaiCode batch.

Two PointersLeetCode 75

Medium

From the first idea to the best one

  1. 01 Brute force · counting sort (two passes) O(n)O(1) space
  2. 02 Better · two-pass swap partition (in place) O(n)O(1) space
  3. 03 Optimized · Dutch National Flag (in place, one pass) O(n)O(1) space
Each approach plays step by step, with its time and space.

What you will learn

  • How to read Sort Colors and spot the two pointers pattern in it
  • Brute force · counting sort (two passes): O(n) time, O(1) space
  • Better · two-pass swap partition (in place): O(n) time, O(1) space
  • Optimized · Dutch National Flag (in place, one pass): O(n) time, O(1) space
  • The pseudocode for each approach, its line lit as the animation runs
  • Practice: write your own pseudocode and get it checked

More Two Pointers

See Sort Colors run, step by step

Sign in and this page opens on the animation, with all 12 Two Pointers problems beside it.

DSA comes with the all labs plan and every ChaiCode batch.