Skip to the code
cf.
+10 XP

#120 Sort Traffic Light States

easy

A status board shows one light per service: 0 for red (down), 1 for yellow (degraded), and 2 for green (healthy). The board should list all red lights first, then yellow, then green.

Write sortLights(lights) that sorts lights in place in one pass, using O(1) extra memory and without calling sort. The tests check lights after your function runs.

Example 1

Input: lights = [2,0,1,2,0]
Output: [0,0,1,2,2]

Reds, then yellows, then greens.

Example 2

Input: lights = [1,1,1]
Output: [1,1,1]

Only yellow lights, so nothing moves.

Constraints

  • 0 <= lights.length <= 100000
  • Each item is 0, 1, or 2.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).