Traffic Light Controlled Intersection — LeetCode 1279 Python Solution

EasyLeetCode PremiumConcurrency
Problem
#1279
Reading time
5 min

The problem

There is an intersection of two roads. First road is road A where cars travel from North to South in direction 1 and from South to North in direction 2.

Example

Input
cars = [1,3,5,2,4], directions = [2,1,2,4,3], arrivalTimes = [10,20,30,40,50]
Output
[

Python solution

Python
from threading import Lock


class TrafficLight:
    def __init__(self):
        self.lock = Lock()
        self.road = 1

    def carArrived(
        self,
        carId: int,  # ID of the car
        # ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
        roadId: int,
        direction: int,  # Direction of the car
        # Use turnGreen() to turn light to green on current road
        turnGreen: 'Callable[[], None]',
        # Use crossCar() to make car cross the intersection
        crossCar: 'Callable[[], None]',
    ) -> None:
        self.lock.acquire()
        if self.road != roadId:
            self.road = roadId
            turnGreen()
        crossCar()
        self.lock.release()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1279. Traffic Light Controlled Intersection?
LeetCode 1279. Traffic Light Controlled Intersection is rated Easy on LeetCode.
What topics does LeetCode 1279. Traffic Light Controlled Intersection cover?
LeetCode 1279. Traffic Light Controlled Intersection is tagged Concurrency on LeetCode.
Is LeetCode 1279. Traffic Light Controlled Intersection a premium problem?
Yes. LeetCode 1279. Traffic Light Controlled Intersection is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview