Traffic Light Controlled Intersection

Easy
ConcurrencyMutexThread CoordinationState Machine

Problem Statement

Design a traffic light controller for a single intersection with two roads:

  • Road A handles directions 1 and 2 (North ↔ South).
  • Road B handles directions 3 and 4 (West ↔ East).

Initially Road A's light is green and Road B's light is red. When a car arrives, call carArrived(carId, roadId, direction, turnGreen, crossCar) where:

  • turnGreen() changes the current road's light to green (should only be called if it isn't already green).
  • crossCar() allows the car to cross the intersection.
class TrafficLight {
    public TrafficLight() {}
    public void carArrived(int carId, int roadId, int direction,
                           Runnable turnGreen, Runnable crossCar) {}
}

Key Entities

  • TrafficLight: Maintains current green-road state with thread-safe transitions.
  • ReentrantLock / synchronized: Ensures only one car crosses at a time and light changes are atomic.
  • currentGreenRoad: Shared variable (volatile or guarded by lock).

Requirements

  1. No two cars from different roads cross at the same time.
  2. turnGreen() must only be called when the road is currently red.
  3. Once a road turns green, subsequent cars on that road can cross without calling turnGreen() again.
  4. Solution must be deadlock-free under concurrent arrivals.

Asked at: Amazon, Microsoft, Google, Uber

!Constraints

- 1 ≤ cars.length ≤ 20 - All carId values are unique. - 1 ≤ directions[i] ≤ 4 (1,2 → Road A; 3,4 → Road B). - arrivalTimes array is non-decreasing. - Each call to carArrived is made from a separate thread.
Output

Run or submit your code to see output here.