Skip to content
BytePatterns

Three Way Flag Sort

MediumSorting#dutch-national-flag#in-place~30m

Problem

A list holds only the values 0, 1 and 2. Arrange it so all the zeros come first, then all the ones, then all the twos. Do it inside the same list with a single pass over the values, without counting how many of each value there are first.

Examples

Input:  values = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Input:  values = [2, 0, 1]
Output: [0, 1, 2]
Why:    every value is a different one, so each has to move
Input:  values = []
Output: []
Why:    edge case, there is nothing to arrange

Hints

0 / 3

Stuck on the idea rather than the code? Dutch National Flag covers it.