Table of Contents
Problem Statement
Bulb Switcher LeetCode Solution – There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
In 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 ith bulb. For the nth round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.
Example:
Test Case 1:
Input:
n = 5
Output:
2
Explanation:
As shown in the above figure, At first, the five bulbs are [0ff, off, off, off, off].
After the first round, the bulbs are [on, on, on, on, on].
After the second round, the bulbs are [on, off, on, off, on].
After the third round, the bulbs are [on, off, off, off, on].
After the fourth round, the bulbs are [on, off, off, on, on].
After the fifth round, the bulbs are [on, off, off, on, off].
So the number of bulbs that are on after the nth round is 2.
Approach
Idea:
If we observe the pattern, we can find that the bulb i is toggled k times, where k is the number of factors of i(except 1).
So if k is odd, the bulb will be off at the end(after off times of toggling).
if k is even, the bulb will be off at the end(after off times of toggling).
if we check for some numbers, we can find out that when k is odd, the number is a perfect square.
So we need to find out how many perfect squares are present in the range [1…n].
Code
Java Program for Bulb Switcher
class Solution { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } }
C++ Program for Bulb Switcher
class Solution { public: int bulbSwitch(int n) { return sqrt(n); } };
Complexity Analysis for Bulb Switcher LeetCode Solution
Time Complexity
Here we are just executing a statement. Time complexity is O(1).
Space Complexity
We are not using any extra space. So Space Complexity is O(1).
Reference https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html