Sort Colors
Real-world version: Triage Band OrderingThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def order_bands(bands: list[int]) -> list[int]:public int[] orderBands(int[] bands)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's