Count Set Bits Brian Kernighan Algorithm in DSA C++ - Time & Space Complexity
We want to understand how fast the Brian Kernighan algorithm counts the number of 1s in a number's binary form.
How does the time taken change as the number gets bigger?
Analyze the time complexity of the following code snippet.
int countSetBits(int n) {
int count = 0;
while (n) {
n = n & (n - 1);
count++;
}
return count;
}
This code counts how many bits are set to 1 in the binary form of the number n by repeatedly turning off the rightmost set bit.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once for each set bit in n.
- How many times: Equal to the number of 1s in the binary representation of n.
The number of operations depends on how many bits are set to 1, not the total number of bits.
| Input Size (n) | Approx. Operations (set bits) |
|---|---|
| 10 (binary 1010) | 2 |
| 100 (binary 1100100) | 3 |
| 1000 (binary 1111101000) | 6 |
Pattern observation: The loop runs as many times as there are 1s, so it grows with the number of set bits, not the total bits.
Time Complexity: O(k) where k is the number of set bits in n.
This means the time depends on how many 1s are in the number, not its size in bits.
[X] Wrong: "The loop runs for all bits of the number, so it is O(log n)."
[OK] Correct: The loop only runs once per set bit, so if the number has few 1s, it runs faster than checking every bit.
Understanding this algorithm shows you can optimize bit operations by focusing on set bits, a useful skill in many coding problems.
"What if we changed the input to always have all bits set (like 2^m - 1)? How would the time complexity change?"
Practice
Solution
Step 1: Understand the algorithm's main operation
The Brian Kernighan algorithm works by clearing the least significant set bit in each iteration.Step 2: Effect of clearing bits
Each clearing reduces the number of set bits by one until the number becomes zero.Final Answer:
It repeatedly clears the least significant set bit until the number becomes zero. -> Option AQuick Check:
Clearing bits one by one counts set bits [OK]
- Counting all bits instead of only set bits
- Using string conversion unnecessarily
- Shifting bits without checking if set
Solution
Step 1: Identify Brian Kernighan's loop
The algorithm uses while (n != 0) and clears the least significant set bit by n = n & (n - 1).Step 2: Confirm increment of count
Each iteration increments count by one for each cleared set bit.Final Answer:
while (n != 0) { n = n & (n - 1); count++; } -> Option CQuick Check:
Loop clears bits and counts [OK]
- Using for loop instead of while
- Counting bits by shifting instead of clearing
- Using modulo instead of bitwise operations
int countSetBits(int n) {
int count = 0;
while (n) {
n = n & (n - 1);
count++;
}
return count;
}
int main() {
int x = 13;
std::cout << countSetBits(x);
return 0;
}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 iteration clears one set bit, so count increments 3 times before n becomes 0.Final Answer:
3 -> Option BQuick Check:
Number of 1s in 1101 = 3 [OK]
- Counting total bits instead of set bits
- Miscounting binary 1s
- Confusing bitwise AND with OR
int countSetBits(int n) {
int count = 0;
while (n > 0) {
n = n & (n + 1);
count++;
}
return count;
}Solution
Step 1: Check bit clearing operation
The correct operation to clear the least significant set bit is n = n & (n - 1), not n + 1.Step 2: Effect of wrong operation
Using n + 1 does not clear bits properly and causes incorrect count or infinite loop.Final Answer:
Using n + 1 instead of n - 1 in bit clearing step. -> Option DQuick Check:
Correct bit clearing uses n & (n - 1) [OK]
- Replacing n - 1 with n + 1
- Confusing loop condition syntax
- Forgetting to increment count
Solution
Step 1: Understand counting set bits per element
Brian Kernighan's algorithm counts set bits in one integer at a time.Step 2: Apply algorithm to each array element
Iterate through the array, count set bits for each element, and sum these counts for total.Final Answer:
Iterate over each element, apply Brian Kernighan's algorithm to count set bits, and sum all counts. -> Option AQuick Check:
Sum of individual counts gives total set bits [OK]
- Counting bits of sum instead of each element
- Using string conversion unnecessarily
- Assuming uniform bit count per element
Ready to prove it?
Pass the test and this pattern moves unknown
