Implement a traffic-light UI with JS
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates front-end web development competencies, including DOM manipulation, CSS-driven UI state, JavaScript timing and asynchronous state management for interactive components.
Constraints
- 1 <= red_duration, green_duration, yellow_duration <= 10^9
- 0 <= len(queries) <= 2 * 10^5
- 0 <= queries[i] <= 10^18
Examples
Input: (5, 4, 2, [0, 4, 5, 8, 9, 10, 11, 12, 20])
Expected Output: ['red', 'red', 'green', 'green', 'yellow', 'yellow', 'red', 'red', 'yellow']
Explanation: The cycle length is 11. Times 0 and 4 are in red, 5 and 8 are in green, 9 and 10 are in yellow, then the cycle repeats at 11.
Input: (1, 1, 1, [0, 1, 2, 3, 4, 5])
Expected Output: ['red', 'green', 'yellow', 'red', 'green', 'yellow']
Explanation: Each light lasts exactly 1 millisecond, so the pattern repeats every 3 milliseconds.
Input: (3, 2, 1, [])
Expected Output: []
Explanation: With no queries, the result is an empty list.
Input: (2, 3, 4, [1, 2, 4, 5, 8, 9, 17, 18])
Expected Output: ['red', 'green', 'green', 'yellow', 'yellow', 'red', 'yellow', 'red']
Explanation: The cycle length is 9. This case checks transitions exactly at boundaries like 2, 5, and 9.
Input: (4, 5, 6, [14, 15, 16, 29, 30, 1000000000])
Expected Output: ['yellow', 'red', 'red', 'yellow', 'red', 'yellow']
Explanation: The cycle length is 15. Time 14 is the last millisecond of yellow, 15 restarts the cycle, and 1000000000 % 15 = 10, which falls in yellow.
Solution
def solution(red_duration, green_duration, yellow_duration, queries):
cycle = red_duration + green_duration + yellow_duration
red_end = red_duration
green_end = red_duration + green_duration
result = []
for t in queries:
position = t % cycle
if position < red_end:
result.append('red')
elif position < green_end:
result.append('green')
else:
result.append('yellow')
return resultTime complexity: O(n), where n is the number of queries. Space complexity: O(n) for the output list.
Hints
- The traffic light pattern repeats every red_duration + green_duration + yellow_duration milliseconds.
- For each query time, reduce it modulo the total cycle length, then check which interval that position falls into.