Traffic Light Controlled Intersection — LeetCode 1279 Python Solution
EasyLeetCode PremiumConcurrency
- Problem
- #1279
- Reading time
- 5 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.