Sort a linked list of 0s, 1s and 2s

medium

You are given the head of a singly linked list whose every node holds one of just three values — 0, 1, or 2. Rearrange the list in place so that all the 0s come first, then all the 1s, and finally all the 2s. Return the head of the rearranged list.

The relative order among equal values does not matter — only that the three groups end up in the order 0s, then 1s, then 2s.

Hints

The values come from an extremely small, fixed set — do you actually need to compare any two of them?
You could count how many 0s, 1s, and 2s exist, then rewrite the list from those counts.
To avoid touching node data at all, split the nodes into three separate chains by value and join them 0s → 1s → 2s.

Common doubts

No. Only the group order (all 0s, then 1s, then 2s) is required; ties can appear in any order. Both the counting and relinking approaches are fine.
It is a valid and common approach and gives O(n) time. The relinking approach is preferred when the nodes carry a payload you must not overwrite, or when the interviewer forbids mutating values.
A comparison sort is O(n log n). Because the values are limited to 0, 1, 2, you can sort in O(n) — comparisons add no information when a 0 always precedes a 1 precedes a 2.

Interview follow-ups

Generalize counting sort: use a size-k tally, or k buckets of relinked sublists concatenated in key order — still O(n) when k is small and known.
It is the linked-list cousin. On an array you can do a single-pass three-pointer partition in place; on a list, relinking into three chains achieves the same one-pass O(1)-space result.

Fun facts

  • Sorting three values without comparisons is the linked-list twin of Dijkstra's 'Dutch National Flag' problem, named for its three horizontal stripes.
  • The count-and-rewrite trick is just counting sort — the same linear-time idea behind radix sort used to order huge integer and string datasets.

Asked at

AmazonMicrosoftAdobeFlipkartGoogle
Frequently Sometimes Occasionally
Example 1
Input: head = [1, 2, 2, 1, 2, 0, 2, 2]
Output: [0, 1, 1, 2, 2, 2, 2, 2]
Every 0 is pulled to the front, every 2 pushed to the back, and the 1s settle in between.
Example 2
Input: head = [2, 2, 0, 1]
Output: [0, 1, 2, 2]
The single 0 leads, the 1 follows, and both 2s trail at the end.
Constraints

- 1 <= number of nodes <= 10^6 - 0 <= node value <= 2

Solve this problem →