All problems
0053MediumArrayTwo PointersSortingQuicksortBubble Sort

Triage Band Ordering

Tracked in this browser only
Write code

Trains the technique from

LeetCode 75Sort Colors

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A walk-in clinic gives every waiting patient a wrist band carrying one of three codes: 0 for immediate, 1 for urgent, 2 for routine. The array bands lists those codes in the order the patients arrived.

Rebuild the queue so that the codes climb: no immediate band may sit behind an urgent or routine band, and no urgent band may sit behind a routine band. Patients sharing a code are interchangeable, so their relative positions do not matter.

Work on bands itself and return it. Touch each position a bounded number of times in one sweep across the array, keep only a fixed set of extra variables, and do not hand the work to a sorting routine from your language's library.

Examples

Example 1

Input
bands = [1, 2, 0, 1, 2, 0]
Output
[0, 0, 1, 1, 2, 2]

Two patients hold an immediate band, two hold urgent and two hold routine, so the queue settles into those three runs.

Example 2

Input
bands = [2, 1, 0]
Output
[0, 1, 2]

The queue arrived in exactly the wrong order, so all three patients change position.

Example 3

Input
bands = [1, 1]
Output
[1, 1]

Both bands carry the same code, so the queue already climbs and nothing moves.

Constraints

  • n == bands.length
  • 1 <= n <= 300
  • bands[i] is either 0, 1, or 2
  • Only a constant amount of extra space may be used
  • `bands` must be rearranged in place and returned

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def order_bands(bands: list[int]) -> list[int]:
Java
public int[] orderBands(int[] bands)
September 7
Apply