Toggle Light Bulbs Problem
#3842
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3842.
You are given an array bulbs of integers between 1 and 100.
There are 100 light bulbs numbered from 1 to 100. All of them are switched off initially.
For each element bulbs[i] in the array bulbs:
- If the
bulbs[i]^thlight bulb is currently off, switch it on. - Otherwise, switch it off.
Return the list of integers denoting the light bulbs that are on in the end, sorted in ascending order. If no bulb is on, return an empty list.
Example 1:
Input: bulbs = [10,30,20,10]
Output: [20,30]
Explanation:
- The bulbs[0] = 10^th light bulb is currently off. We switch it on.
- The bulbs[1] = 30^th light bulb is currently off. We switch it on.
- The bulbs[2] = 20^th light bulb is currently off. We switch it on.
- The bulbs[3] = 10^th light bulb is currently on. We switch it off.
- In the end, the 20^th and the 30^th light bulbs are on.
Example 2:
Input: bulbs = [100,100]
Output: []
Explanation:
- The bulbs[0] = 100^th light bulb is currently off. We switch it on.
- The bulbs[1] = 100^th light bulb is currently on. We switch it off.
- In the end, no light bulb is on.
Constraints:
1 <= bulbs.length <= 1001 <= bulbs[i] <= 100
Solution
Approach: Simulation
Keep an array st of 101 flags, all 0 (off) at the start. For each number x in bulbs, flip st[x] with st[x] ^= 1. After processing the whole array, walk through the indices from 1 to 100 and collect those whose flag is 1. They are visited in increasing order, so the list is already sorted.
Complexity:
- Time:
O(n + M), whereM = 100is the number of bulbs. - Space:
O(M).
class Solution:
def toggleLightBulbs(self, bulbs: List[int]) -> List[int]:
st = [0] * 101
for x in bulbs:
st[x] ^= 1
return [i for i, x in enumerate(st) if x]