← Home

319. Bulb Switcher

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
319

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 319. Bulb Switcher, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 31 / 35 test cases passed.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are bulbSwitch, state, getDivisorCount, sieveOfEratosthenes.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//31 / 35 test cases passed.
03class Solution {
04public:
05    int bulbSwitch(int n) {
06        if(n == 1) return 1;
07        
08        vector<bool> state(n, true);
09        for(int t = 2; t <= n; t++){
10            for(int i = t-1; i < n; i += t){
11                // cout << state[i] << " " << (~state[i]) << " " << !state[i] << endl;
12                //~: bitwise complement, !: not
13                //~1 -> -2, !1 -> 0, so we should use "!" here
14                state[i] = !state[i];
15            }
16        }
17        
18        // for(int i = 0; i < n; i++){
19        //     cout << state[i] << " ";
20        // }
21        // cout << endl;
22        
23        return accumulate(state.begin(), state.end(), 0);
24    }
25};
26
27//count divisor
28//TLE
29//30 / 35 test cases passed.
30class Solution {
31public:
32    vector<int> divisorCount;
33    
34    int getDivisorCount(int n){
35        if(divisorCount[n] == 0){
36            int count = 0; //1
37            double sqrt_n = sqrt(n);
38            
39            for(int i = 1; i <= sqrt_n; i++){
40                if(n % i == 0){
41                    if(i == sqrt_n) count++;
42                    else count += 2;
43                }
44            }
45            
46            divisorCount[n] = count;
47        }
48        return divisorCount[n];
49    };
50    
51    int bulbSwitch(int n) {
52        //sum of divisor count from 1 to n
53        divisorCount = vector<int>(n+1, 0);
54        int ans = 0;
55        
56        for(int i = 1; i <= n; i++){
57            int count = getDivisorCount(i);
58            // cout << i << " " << count << endl;
59            if(count % 2 == 1){
60                ans++;
61            }
62        }
63        
64        return ans;
65    }
66};
67
68//Count Divisors of n in O(n^1/3)
69//TLE
70//27 / 35 test cases passed.
71//https://www.geeksforgeeks.org/count-divisors-n-on13/
72class Solution {
73public:
74    vector<int> primes;
75    vector<int> divisorCount;
76    
77    void sieveOfEratosthenes(int n, vector<int>& primes){
78        vector<bool> isPrime = vector<bool>(n+1, true);
79        // vector<bool> isPrimeSquare = vector<bool>((long long)n*n+1, false);
80        
81        //isPrime should be initialized as false
82        //isPrimeSquare should be initialized as true
83        isPrime[1] = false;
84        
85        //mark prime's multiples as non-prime
86        for(int p = 2; p * p <= n; p++){
87            if(isPrime[p]){
88                //start from current prime's two times!
89                for(int i = p*2; i <= n; i+=p){
90                    isPrime[i] = false;
91                }
92            }
93        }
94        
95        for(int p = 2; p <= n; p++){
96            if(isPrime[p]){
97                // cout << p << " ";
98                // isPrimeSquare[p*p] = true;
99                primes.push_back(p);
100            }
101        }
102        // cout << endl;
103    }
104    
105    int getDivisorCount(int n){
106        if(n == 1) return 1;
107        if(divisorCount[n] != 0) return divisorCount[n];
108        
109        int org_n = n;
110        
111        //split n into x*y
112        
113        int count = 1;
114        /*
115        counting factors of x
116        if x = p^m + q^n, 
117        then divisor count of x is (m+1)*(n+1)
118        */
119        for(int i = 0; pow(primes[i], 3) <= n; i++){
120            int pow_i = 1;
121            while(n % primes[i] == 0){
122                n /= primes[i];
123                pow_i++;
124            }
125            //now pow(primes[i], pow_i-1) becomes n
126            
127            count *= pow_i;
128        }
129        
130        // cout << "n: " << org_n << ". x: " << org_n/n << ", y: " << n << endl;
131        
132        //counting factors of y
133        
134        if(find(primes.begin(), primes.end(), n) != primes.end()){
135            //y is prime
136            count *= 2;
137        }else if(n/sqrt(n) == sqrt(n) && find(primes.begin(), primes.end(), sqrt(n)) != primes.end()){
138            //y is a prime's square
139            count *= 3;
140        }else if(n != 1){
141            //y is the product of two distinct prime numbers
142            count *= 4;
143        }
144        
145        divisorCount[n] = count;
146        
147        return count;
148    };
149    
150    int bulbSwitch(int n) {
151        //sum of divisor count from 1 to n
152        divisorCount = vector<int>(n+1, 0);
153        
154        sieveOfEratosthenes(n, primes);
155        
156        int ans = 0;
157        
158        for(int i = 1; i <= n; i++){
159            int count = getDivisorCount(i);
160            // cout << i << " " << count << endl;
161            if(count % 2 == 1){
162                ans++;
163            }
164        }
165        
166        return ans;
167    }
168};
169
170//Math
171//https://leetcode.com/problems/bulb-switcher/discuss/77104/Math-solution..
172class Solution {
173public:
174    int bulbSwitch(int n) {
175        /*
176        we want to find how many i in the range [1...n] whose
177        divisor count is odd.
178        A number's divisor count is odd iff it's square.
179        So we want to find out how many i in the range [1...n] is square.
180        And the count of square root in the range [1...sqrt(n)] is same as the count of square in the range[1...n],
181        so we can just give sqrt(n) as our answer
182        */
183        return sqrt(n);
184    }
185};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.