Difficulty: Easy | Acceptance: 83.10% | Paid: No Topics: N/A
You are given a string currentRoad representing the current color of the traffic signal and an integer time representing the number of seconds that have passed. The traffic signal changes color every second in the following order: Green -> Yellow -> Red -> Green. Return the color of the traffic signal after time seconds.
- Examples
- Constraints
- Simulation (Brute Force)
- Modulo Arithmetic (Optimal)
Examples
Example 1
Input:
timer = 60
Output:
"Red"
Explanation: Since timer = 60, and 30 < timer <= 90, the answer is “Red”.
Example 2
Input:
timer = 5
Output:
"Invalid"
Explanation: Since timer = 5, it does not satisfy any of the given conditions, the answer is “Invalid”.
Constraints
- 0 <= timer <= 1000
Simulation (Brute Force)
Intuition We can simulate the passage of time second by second, updating the color of the traffic signal according to the fixed cycle Green -> Yellow -> Red -> Green.
Steps
- Initialize a variable to hold the current color.
- Loop from 0 to time - 1.
- In each iteration, update the current color to the next color in the sequence.
- Return the final color.
class Solution:
def trafficSignalColor(self, currentRoad: str, time: int) -> str:
colors = ["Green", "Yellow", "Red"]
idx = colors.index(currentRoad)
for _ in range(time):
idx = (idx + 1) % 3
return colors[idx]Complexity
- Time: O(time) - We iterate once for every unit of time.
- Space: O(1) - We only store a few variables.
- Notes: This approach will Time Limit Exceed (TLE) for large values of time (up to 10⁹).
Modulo Arithmetic (Optimal)
Intuition Since the traffic signal cycles every 3 seconds, we can use the modulo operator to find the final state without iterating through every second. We map the colors to indices 0, 1, and 2, add the time, and take modulo 3 to find the new index.
Steps
- Map the input string currentRoad to an integer index (0 for Green, 1 for Yellow, 2 for Red).
- Calculate the new index by adding time to the current index and taking the result modulo 3.
- Map the resulting index back to the corresponding color string and return it.
class Solution:
def trafficSignalColor(self, currentRoad: str, time: int) -> str:
colors = ["Green", "Yellow", "Red"]
idx = colors.index(currentRoad)
new_idx = (idx + time) % 3
return colors[new_idx]Complexity
- Time: O(1) - Mathematical calculation is performed in constant time.
- Space: O(1) - Only a fixed-size array and variables are used.
- Notes: This is the optimal solution as it handles the maximum constraint of time efficiently.