Skip to content

3894. Traffic Signal Color

Description

You are given an integer timer representing the remaining time (in seconds) on a traffic signal.

The signal follows these rules:

  • If timer == 0, the signal is "Green"
  • If timer == 30, the signal is "Orange"
  • If 30 < timer <= 90, the signal is "Red"

Return the current state of the signal. If none of the above conditions are met, return "Invalid".

 

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

Solutions

Solution 1: Simulation

Thinking

Return the light color from a few discrete tests on \(\textit{timer}\), otherwise \(\texttt{Invalid}\).

The predicates are disjoint; check \(0\), then \(30\), then \((30,90]\).

No extra state is required.

Constant time.

We determine the answer according to the conditions described in the problem and return the corresponding string.

The time complexity is \(O(1)\), and the space complexity is \(O(1)\).

1
2
3
4
5
6
7
8
9
class Solution:
    def trafficSignal(self, timer: int) -> str:
        if timer == 0:
            return "Green"
        if timer == 30:
            return "Orange"
        if 30 < timer <= 90:
            return "Red"
        return "Invalid"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
    public String trafficSignal(int timer) {
        if (timer == 0) {
            return "Green";
        }
        if (timer == 30) {
            return "Orange";
        }
        if (timer > 30 && timer <= 90) {
            return "Red";
        }
        return "Invalid";
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    string trafficSignal(int timer) {
        if (timer == 0) {
            return "Green";
        }
        if (timer == 30) {
            return "Orange";
        }
        if (timer > 30 && timer <= 90) {
            return "Red";
        }
        return "Invalid";
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func trafficSignal(timer int) string {
    switch {
    case timer == 0:
        return "Green"
    case timer == 30:
        return "Orange"
    case timer > 30 && timer <= 90:
        return "Red"
    default:
        return "Invalid"
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function trafficSignal(timer: number): string {
    if (timer === 0) {
        return 'Green';
    }
    if (timer === 30) {
        return 'Orange';
    }
    if (timer > 30 && timer <= 90) {
        return 'Red';
    }
    return 'Invalid';
}

Comments