Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Sort Colors

LeetCode #75Medium
Dutch National Flag · in-place · three pointers

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.

Asked atMicrosoftAmazonMeta
step 1 / 82
2
0
1
0
1
2
0
[0][1][2][3][4][5][6]
Brute force · counting sort (two passes)
1given arr
2count ← [0, 0, 0]
3for v in arr: count[v]++
4write count[0] zeros, then count[1] ones, then count[2] twos
5return arr
state
  • n7

line 1Sort an array of 0 (red), 1 (white), 2 (blue) — in place. Value-set is tiny, so first idea: counting sort.