Advertisement

Bulb Switcher - LeetCode 319 Solution

Bulb Switcher - Complete Solution Guide

Bulb Switcher is LeetCode problem 319, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds. Example 1: Input: n = 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After the first round, the three bulbs are [o

Detailed Explanation

The problem asks us to simulate a series of bulb toggling rounds. Initially, all 'n' bulbs are off. In the first round, all bulbs are turned on. In the second round, every second bulb is toggled (turned off). In the third round, every third bulb is toggled, and so on. After 'n' rounds, we need to determine how many bulbs are left on.

Solution Approach

The solution leverages the mathematical property that a number has an odd number of divisors if and only if it's a perfect square. Therefore, we need to count the number of perfect squares less than or equal to 'n'. This can be done by finding the integer square root of 'n'.

Step-by-Step Algorithm

  1. Step 1: Calculate the integer square root of 'n'. This effectively finds the largest integer 'x' such that x*x <= n.
  2. Step 2: Return the integer square root. This value represents the count of perfect squares from 1 to 'n' (1*1, 2*2, 3*3, ... x*x).

Key Insights

  • Insight 1: A bulb will be ON at the end if it has been toggled an odd number of times. It will be OFF if toggled an even number of times.
  • Insight 2: The number of times a bulb is toggled is equal to the number of its divisors. For example, bulb number 12 is toggled in rounds 1, 2, 3, 4, 6, and 12 (6 divisors).
  • Insight 3: A number has an odd number of divisors if and only if it is a perfect square. For example, 9 has divisors 1, 3, and 9 (3 divisors). If a number is not a perfect square, its divisors come in pairs (e.g., for 12, the pairs are 1 and 12, 2 and 6, 3 and 4). Perfect squares like 9 only have the divisor 3 once, making the count odd.

Complexity Analysis

Time Complexity: O(1)

Space Complexity: O(1)

Topics

This problem involves: Math, Brainteaser.

Companies

Asked at: Accenture.