← DiffPush

Sort 0 1 2 in LL

Standard Bar Linked List · Medium Problems of LL O(N) · O(1)

Sorting the Bay by Signal Class

A warehouse chain lists pallets each carrying one of three signal classes — 0, 1, or 2 — and the floor plan demands all 0-class pallets up front, 2-class at the far end, 1-class in between. Because only three classes exist, a tally pass followed by an overwrite pass re-stamps the chain in class order without building anything new.

Input: An array head of node values, each of which is 0, 1, or 2.

Output: The values after segregation: all 0s first, then all 1s, then all 2s.

Constraints

Examples

Example 1

Input: {"head":[1,2,2,1,2,0,2,2]}
Output: [0,1,1,2,2,2,2,2]
One zero, two ones, five twos — the rewrite lays them out in class order.

Example 2

Input: {"head":[2,2,0]}
Output: [0,2,2]
No 1-class pallets exist; the zero leads and the twos follow.

Solve this in your browser →

Also on LeetCode ↗