← Questions

Sort colors (three-way partition in place)

0
MicrosoftCodingLast asked Apr 2026

A coding interview question asked in Microsoft's technical phone screen, last asked Apr 2026. It tests arrays, two pointers and sorting.

An array items holds only the values 0, 1 and 2, each standing for a category. Rearrange it in place so all 0s come first, then all 1s, then all 2s, in one pass and O(1) extra space, without counting and rewriting.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • sort_colors(items: list[int]) -> None — modifies items in place.

Example

items = [2, 0, 2, 1, 1, 0]
sort_colors(items)   # items == [0, 0, 1, 1, 2, 2]

items = [2, 0, 1]
sort_colors(items)   # items == [0, 1, 2]

items = [0]
sort_colors(items)   # items == [0]

Constraints

  • 0 <= len(items) <= 10^5; every element is 0, 1 or 2.
  • One pass, O(1) extra space.

Clarifying questions

  • Is a two-pass counting sort acceptable? (Not here.)
  • Do elements carry other data, so the order within a category matters?
  • Can the array be empty?

What a strong answer covers

  • The Dutch national flag partition with three pointers low, mid, high, and its invariant: [0, low) are 0s, [low, mid) are 1s, (high, end] are 2s, [mid, high] unknown.
  • The step rules: a 0 swaps to low and both advance; a 1 advances mid; a 2 swaps to high and only high moves, because the swapped-in value is unchecked.
  • O(n) time, O(1) space; the loop ends when mid > high.
  • Why it is not stable, and when that matters.
  • Tests: empty, all one value, already sorted, reverse sorted.

Follow-ups

  • Sort an array with k distinct categories in place.
  • Partition around a pivot value (< p, = p, > p) as in quicksort's three-way partition.
  • Keep the relative order within each category (stable) with O(1) extra space: what does it cost?

Where it's asked

What it tests

arrays · two pointers · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding