Taro Logo

Toggle Light Bulbs

Easy
Asked by:
Juspay
0 views
Topics:
Arrays

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]th light 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] = 10th light bulb is currently off. We switch it on.
  • The bulbs[1] = 30th light bulb is currently off. We switch it on.
  • The bulbs[2] = 20th light bulb is currently off. We switch it on.
  • The bulbs[3] = 10th light bulb is currently on. We switch it off.
  • In the end, the 20th and the 30th light bulbs are on.

Example 2:

Input: bulbs = [100,100]

Output: []

Explanation:

  • The bulbs[0] = 100th light bulb is currently off. We switch it on.
  • The bulbs[1] = 100th light bulb is currently on. We switch it off.
  • In the end, no light bulb is on.

Constraints:

  • 1 <= bulbs.length <= 100
  • 1 <= bulbs[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of $n$, and could $n$ be zero or negative?
  2. Are the rounds 1-indexed (from 1 to $n$) or 0-indexed (from 0 to $n-1$), and does the $i$-th round mean we toggle every $i$-th bulb starting from the $i$-th bulb itself?
  3. Should the function return the exact count of bulbs that remain on, or should it return a collection (like a list or array) of the specific bulb indices or states?
  4. Is the memory complexity constrained, or can we afford an array of size $n$ to explicitly simulate the state of each bulb?
  5. Are there any specific time complexity expectations beyond the most optimal mathematical solution?

Brute Force Solution

Approach

The brute force approach to solving the toggle light bulbs problem involves physically following the exact rules of the puzzle step-by-step for every single bulb. We literally walk down the line of bulbs over and over, flipping the correct ones just like the instructions tell us to, until we have gone through every round of changes.

Here's how the algorithm would work step-by-step:

  1. Line up all the light bulbs in a row and ensure they all start in the off position.
  2. Begin the first round by walking down the line and flipping the switch on every single light bulb.
  3. Move on to the second round where you walk down the line again, but this time you only touch every second bulb.
  4. Continue this exact process for the third round by visiting every third bulb and flipping its switch.
  5. Keep repeating these walking rounds, each time increasing your step size by one, until you have finished checking every single bulb according to the rules.
  6. At the very end, walk down the line one final time to count how many light bulbs happened to end up in the glowing state.

Code Implementation

def toggle_light_bulbs_brute_force(total_bulbs):
    light_bulb_states = [False] * total_bulbs

    # Iterate through each round up to the total number of bulbs to simulate the exact walking steps
    for current_round in range(1, total_bulbs + 1):
        for bulb_index in range(current_round - 1, total_bulbs, current_round):
            light_bulb_states[bulb_index] = not light_bulb_states[bulb_index]

    glowing_bulb_count = 0

    # Count the final glowing bulbs to determine the total outcome of our simulation rounds
    for bulb_state in light_bulb_states:
        if bulb_state:
            glowing_bulb_count += 1

    return glowing_bulb_count

Big(O) Analysis

Time Complexity
O(n²) – To simulate the puzzle for n light bulbs, we execute n separate rounds where each round k visits and toggles every kth bulb. This results in the first round visiting n bulbs, the second round visiting n/2 bulbs, the third round visiting n/3 bulbs, and so on up to the nth round. Summing the operations across all rounds yields approximately n * (1 + 1/2 + 1/3 + ... + 1/n) or more simply bounded by nested iterations proportional to n * n/2 total steps. Dropping the constant factor gives a final Big O time complexity of O(n²).
Space Complexity
O(1) – To determine how many bulbs remain glowing, the brute force approach described requires physically following the rules by storing the state of all N light bulbs in an auxiliary array or list of size N. However, by recognizing the mathematical pattern where only perfect square bulbs remain on, the optimal solution requires only a few primitive integer variables for loop counters and math operations regardless of the input size N. Therefore, the extra memory required beyond the input itself remains constant. This leads to an optimal auxiliary space complexity of O(1).

Optimal Solution

Approach

Instead of physically flipping the light bulbs one by one, the optimal approach relies on a clever mathematical pattern to figure out which ones remain on. By thinking about how many times each bulb gets touched, you can instantly know its final state without doing any heavy lifting.

Here's how the algorithm would work step-by-step:

  1. Imagine a row of light bulbs, all starting out turned off.
  2. Think about the counting numbers starting from one, and how each number interacts with the bulbs.
  3. A specific bulb will get touched or flipped only by the numbers that can evenly divide its position in the line.
  4. For most bulbs, the numbers that flip them always come in neat pairs, meaning a bulb gets flipped an even number of times and ultimately ends up turned off.
  5. However, look closely at the positions that are perfect squares, like four or nine.
  6. For these special square positions, one of the dividing numbers pairs with itself, which means that specific divisor only appears once instead of twice.
  7. Because of that single unpaired flip, bulbs sitting at square positions end up getting flipped an odd number of times, leaving them turned on at the very end.
  8. Therefore, the secret to finding all the glowing bulbs is simply identifying which positions are perfect squares.
  9. By just listing out those square positions, you skip all the tedious flipping and immediately know the final answer.

Code Implementation

def toggle_light_bulbs(total_bulb_count):
    # Perfect squares have an odd number of divisors, leaving them turned on.
    glowing_bulbs_list = []

    current_integer = 1

    # Only check numbers whose squares do not exceed the total bulb count.
    while (current_integer * current_integer) <= total_bulb_count:
        
        glowing_bulbs_list.append(current_integer * current_integer)

        current_integer += 1

    # Return the exact positions of all bulbs that remain glowing.
    return glowing_bulbs_list

Big(O) Analysis

Time Complexity
O(sqrt(n)) – In this optimal mathematical approach, we do not simulate the flipping of bulbs or iterate through all n bulbs. Instead, the cost is entirely driven by finding which numbers up to n are perfect squares. By iterating through integers starting from one whose squares are less than or equal to n, the loop runs roughly sqrt(n) times. This totals approximately sqrt(n) operations without any nested loops or heavy lifting, which simplifies to O(sqrt(n)).
Space Complexity
O(1) – The algorithm relies entirely on a mathematical pattern to determine which bulbs remain on by checking for perfect squares up to N, requiring no additional data structures that scale with the input. We only allocate a few primitive variables to track loop indices and intermediate square values. Because these memory allocations remain constant regardless of how large N grows, the auxiliary space complexity is strictly constant. Ultimately, this approach avoids storing intermediate results or tracking individual bulb states, resulting in an O(1) space footprint.

Edge Cases

n is equal to 0 or negative
How to Handle:
Return 0 immediately because there are no light bulbs to operate on.
n is equal to 1
How to Handle:
Return 1 since the single bulb is toggled once in the first round and remains on.
n is a very large integer up to the 32-bit signed integer limit
How to Handle:
Use a mathematical square root approach to calculate the result in O(1) time and avoid Time Limit Exceeded errors.
n is a perfect square
How to Handle:
The integer square root will be exact, and the bulb will remain on because it gets toggled an odd number of times.
n is not a perfect square
How to Handle:
Taking the integer square root via floor operation accurately yields the exact count of bulbs left on.
n is extremely large where naive simulation would cause memory or time limits
How to Handle:
The O(1) math solution bypasses any memory allocation and prevents simulation bottlenecks entirely.
Language-specific integer overflow during intermediate calculations
How to Handle:
Using standard integer types is sufficient since operations involve simple square roots well within standard limits.