EasyNo. 1279LeetCode Premium

Traffic Light Controlled Intersection — LeetCode 1279 Python Solution

Topics
Concurrency
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Related problems
No.ProblemDifficulty
1114Print in OrderEasy
1115Print FooBar AlternatelyMedium
1116Print Zero Even OddMedium
1117Building H2OMedium
1287Element Appearing More Than 25% In Sorted ArrayEasy
0057Insert IntervalMedium

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.

Free to download. Check it runs on your machine, then pick a plan.