Count Set Bits Brian Kernighan Algorithm in DSA Javascript - Time & Space Complexity
We want to understand how fast the Brian Kernighan algorithm counts the number of 1s in a binary number.
How does the time it takes change as the number gets bigger?
Analyze the time complexity of the following code snippet.
function countSetBits(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count++;
}
return count;
}
This code counts how many bits are set to 1 in the binary form of a number by repeatedly turning off the rightmost set bit.
- Primary operation: The while loop that runs once for each set bit in the number.
- How many times: Equal to the number of 1s in the binary representation of the input number.
The number of loop runs depends on how many 1 bits the number has, not its size in bits.
| Input Size (n) | Approx. Operations (set bits) |
|---|---|
| 10 (1010 binary) | 2 |
| 15 (1111 binary) | 4 |
| 1023 (1111111111 binary) | 10 |
Pattern observation: The execution grows with the number of 1 bits, which can be much less than the total bits in the number.
Time Complexity: O(k)
This means the time depends on the count of set bits (k), not the total bits in the number.
[X] Wrong: "The loop runs once for every bit in the number, so it is O(log n)."
[OK] Correct: The loop only runs for each set bit, which can be fewer than total bits, so it can be faster than O(log n).
Knowing this algorithm shows you can use clever bit tricks to improve speed, a skill valued in coding challenges and interviews.
"What if we changed the input to always have only one set bit? How would the time complexity change?"
Practice
Solution
Step 1: Understand the algorithm's main operation
The algorithm clears the least significant set bit by doing n = n & (n-1) repeatedly.Step 2: Effect of clearing bits
Each operation removes one set bit, counting how many times this happens gives the total set bits.Final Answer:
It repeatedly clears the least significant set bit until the number becomes zero -> Option CQuick Check:
Clearing bits counts set bits [OK]
- Counting total digits instead of set bits
- Counting zeros instead of ones
- Using string length instead of bit operations
Solution
Step 1: Identify the bit clearing operation
The correct operation to clear the least significant set bit is n = n & (n - 1).Step 2: Verify other options
Other options do not clear the least significant set bit correctly.Final Answer:
n = n & (n - 1); -> Option BQuick Check:
Use AND with (n-1) to clear bit [OK]
- Using OR or XOR instead of AND
- Adding instead of subtracting 1
- Confusing bitwise operators
function countSetBits(n) {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(13));Solution
Step 1: Convert 13 to binary
13 in binary is 1101, which has three set bits (1s).Step 2: Apply Brian Kernighan's algorithm
Each loop clears one set bit, so count increments 3 times before n becomes 0.Final Answer:
3 -> Option AQuick Check:
13 (1101) has 3 set bits [OK]
- Counting total bits instead of set bits
- Miscounting binary representation
- Off-by-one errors in loop
function countSetBits(n) {
let count = 0;
while (n != 0) {
n = n & (n + 1);
count++;
}
return count;
}Solution
Step 1: Check the bit clearing operation
The code uses n = n & (n + 1), which does not clear the least significant set bit correctly.Step 2: Correct operation
The correct operation is n = n & (n - 1) to clear the least significant set bit.Final Answer:
Using n & (n + 1) instead of n & (n - 1) -> Option DQuick Check:
Use n & (n-1) to clear bits [OK]
- Using n & (n + 1) which is incorrect
- Confusing loop types
- Forgetting to return count
const arr = [3, 5, 7];
// Choose the correct code to count all set bits
A) let total = 0;
for(let n of arr) {
while(n > 0) {
n = n & (n - 1);
total++;
}
}
console.log(total);
B) let total = 0;
for(let n of arr) {
total += n.toString(2).length;
}
console.log(total);
C) let total = 0;
for(let n of arr) {
while(n > 0) {
n = n | (n - 1);
total++;
}
}
console.log(total);
D) let total = 0;
for(let n of arr) {
total += n & (n - 1);
}
console.log(total);Solution
Step 1: Identify the correct implementation
The implementation usingwhile(n > 0) { n = n & (n - 1); total++; }correctly applies Brian Kernighan's algorithm by clearing the least significant set bit repeatedly for each array element and incrementing the total count each time.Step 2: Eliminate incorrect options
The option usingn.toString(2).lengthcounts all bits including zeros; usingn | (n - 1)does not clear set bits correctly; addingn & (n - 1)directly does not count the number of set bits.Final Answer:
Correctly counts set bits using Brian Kernighan's method -> Option AQuick Check:
Clear bits and count in loop [OK]
- Counting total binary length instead of set bits
- Using OR instead of AND for clearing bits
- Adding bitwise results instead of counts
Ready to prove it?
Pass the test and this pattern moves unknown
