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 binary number.
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 integer n using Brian Kernighan's method.
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 1 bits in n, not the total number of bits.
Execution depends on how many 1s are in the number, not just its size.
| 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 grows with how many 1s are in the number, which can be much less than the total bits.
[X] Wrong: "The loop always runs for all bits in the number (like 32 or 64 times)."
[OK] Correct: The loop only runs once per set bit, so if the number has few 1s, it runs fewer times.
Understanding this algorithm shows you can optimize by focusing on important parts of data, a skill valued in problem solving.
"What if we changed the input to always have half of its bits set? How would the time complexity change?"
Practice
Solution
Step 1: Understand the algorithm's main operation
The algorithm uses n = n & (n-1) to clear the least significant set bit in each iteration.Step 2: Effect of clearing bits
Each operation 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 = It repeatedly clears the least significant set bit until the number becomes zero. [OK]
- Counting zeros instead of ones
- Shifting without clearing bits
- Confusing decimal digits with bits
Solution
Step 1: Recall the bit clearing operation
The Brian Kernighan algorithm clears the least significant set bit by n = n & (n - 1).Step 2: Verify other options
Options A, B, and D do not clear the least significant set bit correctly.Final Answer:
n = n & (n - 1); -> Option AQuick Check:
Use n & (n-1) to clear bits [OK]
- Using +1 instead of -1
- Using OR or XOR instead of AND
- Confusing bitwise operators
unsigned int n = 13; // binary 1101
int count = 0;
while (n) {
n = n & (n - 1);
count++;
}
printf("%d", count);Solution
Step 1: Analyze initial value and binary form
13 in binary is 1101, which has three set bits (1s).Step 2: Count iterations clearing bits
Each loop clears one set bit: 1101 -> 1100 -> 1000 -> 0000, so loop runs 3 times.Final Answer:
3 -> Option DQuick Check:
Number of set bits in 13 = 3 [OK]
- Counting total bits instead of set bits
- Off-by-one in loop count
- Misreading binary representation
int countSetBits(int n) {
int 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 for clearing bits
The correct operation is n = n & (n - 1) to clear the least significant set bit.Final Answer:
Using n + 1 instead of n - 1 in bit clearing step. -> Option BQuick Check:
Use n & (n-1) to clear bits, not n & (n+1) [OK]
- Using +1 instead of -1
- Ignoring loop condition correctness
- Forgetting to initialize count
Solution
Step 1: Identify Brian Kernighan's approach
For each element, repeatedly clear least significant set bit and count until zero, then sum counts.: For each element, repeatedly clear the least significant set bit until zero and count (using n = n & (n-1)), then sum the counts across elements. This is the direct application of Brian Kernighan's algorithm.Step 2: Why it is most efficient using Brian Kernighan
B (strings) is slow; C (shifts) is O(word size) always; D (lookup) is fast but a separate method, not Brian Kernighan's. Brian Kernighan excels for sparse bits (O(set bits) time).Final Answer:
For each element, repeatedly clear least significant set bit and count until zero, then sum counts. -> Option CQuick Check:
Brian Kernighan on array: apply n & (n-1) loop per element [OK]
- Using string conversion which is slow
- Bit shifting each bit without optimization
- Confusing lookup table with Brian Kernighan method
Ready to prove it?
Pass the test and this pattern moves unknown
