Skip to the solution
EasyMachine Coding11 min read

Build a Traffic Light

1.0k views

The problem

Question presented to candidate: "Build a traffic light. It cycles red, green, yellow and back to red on its own, and each colour has its own duration. Add a Pause button that freezes it where it is, so Resume continues with the time that was left, and a Next button that skips to the next colour straight away."

Requirements:

  • Three lamps, exactly one lit; red 3 s, then green 2.5 s, then yellow 1 s, then red again, forever.
  • Durations and the order live in one configuration object.
  • Pause freezes the current colour and remembers the time left; Resume continues from there.
  • Next moves to the next colour immediately and gives it its full duration (works while paused too).
  • A text status for screen readers ("Red: stop"); nothing left running after unmount.

What a strong answer should cover:

  • Modelling the light as a finite state machine: a config map { red: { ms, next }, ... } so adding a state is a data change, not new if branches.
  • One setTimeout per state (not a setInterval), re-armed when the state changes and cleared before every re-arm.
  • Pause that banks the remaining time (from a recorded endsAt) instead of restarting the colour.
  • Why the timer must be cleaned up on every transition (otherwise Next plus the old timer skip a colour).
  • Separating what is state (light, remaining, running) from what is not (the endsAt timestamp, which is never rendered).
  • Accessibility: lamps are decorative, the status text is a role="status" live region.

Clarifying questions expected:

  • "Should Next while paused stay paused?"
  • "Do we need a pedestrian button or a flashing-yellow night mode?"
  • "Should the durations be configurable by the user or only in code?"

Code / implementation expected: Yes. A working component driven by a state-machine config, with pause/resume that keeps the remaining time, Next and cleanup.

  • React
  • Timers
  • State Machine

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 9 sections

React solution

Every file of the working solution. Open it in the playground to run and change it.

ReactComplete solution
import TrafficLight from "./src/components/TrafficLight";

export default function App() {
  return (
    <main className="page">
      <TrafficLight />
    </main>
  );
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 7 of 107 in Machine coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Build a Progress Bar

Continue