← DiffPush

Sort 0 1 2

Standard Bar Arrays · Medium O(n) · O(1)

Triaging a Packet Queue by Priority Class

A router holds packets tagged with one of three priority classes, encoded as 0, 1 and 2. The scheduler must rewrite the queue so class 0 comes first, then class 1, then class 2, with no queue-sized scratch buffer and no library sort. Reorder the queue in place in a single pass.

Input: An array nums of n integers where each value is 0, 1 or 2.

Output: The same array reordered so all 0s come first, followed by all 1s and then all 2s.

Constraints

Examples

Example 1

Input: {"nums":[2,0,2,1,1,0]}
Output: [0,0,1,1,2,2]
Both zeros are pulled to the front, both twos to the back, and the ones settle in the middle.

Example 2

Input: {"nums":[2,0,1]}
Output: [0,1,2]
Only three packets, but each class still has to land in its own band.

Solve this in your browser →

Also on LeetCode ↗