LeetCode 1279: Traffic Light Controlled Intersection Solution

Master LeetCode problem 1279 (Traffic Light Controlled Intersection), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1279. Traffic Light Controlled Intersection

Problem Explanation

Explanation

To implement a traffic light controlled intersection, we can maintain a queue for each road entering the intersection. The cars will wait in these queues until the traffic light for their road turns green. We will simulate the traffic light switching at a regular interval.

We can use a variable to keep track of the current active road and another variable to keep track of the time elapsed since the last traffic light change. When the time limit for the current road is reached, we switch to the next road and reset the timer.

Solution Code

class TrafficLight {
    private int currentRoad;
    private int timeLimit;
    private int timeElapsed;
    
    public TrafficLight() {
        currentRoad = 1;
        timeLimit = 0;
        timeElapsed = 0;
    }
    
    public void carArrived(int roadName, int time) {
        if (roadName != currentRoad) {
            timeElapsed = 0;
            currentRoad = roadName;
        }
        
        if (timeElapsed + time <= timeLimit) {
            timeElapsed += time;
        } else {
            timeLimit = time;
            timeElapsed = time;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1279 (Traffic Light Controlled Intersection)?

This page provides optimized solutions for LeetCode problem 1279 (Traffic Light Controlled Intersection) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1279 (Traffic Light Controlled Intersection)?

The time complexity for LeetCode 1279 (Traffic Light Controlled Intersection) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1279 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1279 in Java, C++, or Python.

Back to LeetCode Solutions