319. Bulb Switcher LeetCode Solution
In this guide, you will get 319. Bulb Switcher LeetCode Solution with the best time and space complexity. The solution to Bulb Switcher problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Bulb Switcher solution in C++
- Bulb Switcher solution in Java
- Bulb Switcher solution in Python
- Additional Resources
Problem Statement of Bulb Switcher
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 [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 1
Constraints:
0 <= n <= 109
Complexity Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
319. Bulb Switcher LeetCode Solution in C++
class Solution {
public:
int bulbSwitch(int n) {
// The k-th bulb can only be switched when k % i == 0.
// So, we can rephrase the problem:
// To find number of numbers <= n that have odd factors.
// Obviously, only square numbers have odd factor(s).
// e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10
return sqrt(n);
}
};
/* code provided by PROGIEZ */
319. Bulb Switcher LeetCode Solution in Java
class Solution {
public int bulbSwitch(int n) {
// The k-th bulb can only be switched when k % i == 0.
// So, we can rephrase the problem:
// To find number of numbers <= n that have odd factors.
// Obviously, only square numbers have odd factor(s).
// e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10
return (int) Math.sqrt(n);
}
}
// code provided by PROGIEZ
319. Bulb Switcher LeetCode Solution in Python
class Solution:
def bulbSwitch(self, n: int) -> int:
# The k-th bulb can only be switched when k % i == 0.
# So, we can rephrase the problem:
# To find number of numbers <= n that have odd factors.
# Obviously, only square numbers have odd factor(s).
# e.g. n = 10, only 1, 4, and 9 are square numbers that <= 10
return math.isqrt(n)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.