#3842

Toggle Light Bulbs

Easy
ArrayHash TableSortingSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a set to efficiently track the state of each bulb. This allows for quick toggling and retrieval of the final states.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty set to track the on bulbs.
  2. 2Step 2: For each bulb in the input array, toggle its presence in the set.
  3. 3Step 3: Return the sorted list of bulbs in the set.
solution.py8 lines
1def toggle_bulbs(bulbs):
2    on_bulbs = set()
3    for bulb in bulbs:
4        if bulb in on_bulbs:
5            on_bulbs.remove(bulb)
6        else:
7            on_bulbs.add(bulb)
8    return sorted(on_bulbs)

Complexity note: The complexity is O(n) since we only traverse the input array once and use a set for constant time toggling.

  • 1Using a set allows efficient toggling.
  • 2Sorting the final result is straightforward.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.