Bit manipulation techniques - Time & Space Complexity
Bit manipulation techniques use operations on bits to solve problems efficiently.
We want to know how the time needed changes as the number of bits grows.
Analyze the time complexity of the following code snippet.
unsigned int countSetBits(unsigned int n) {
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
This code counts how many bits are set to 1 in the number n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that checks each bit of n.
- How many times: Once for each bit until n becomes zero.
Explain the growth pattern intuitively.
| Input Size (bits in n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 32 | About 32 checks |
| 64 | About 64 checks |
Pattern observation: The number of operations grows linearly with the number of bits in n.
Time Complexity: O(k) where k is the number of bits in the input number.
This means the time grows directly with how many bits the number has.
[X] Wrong: "Bit operations always run in constant time no matter the number size."
[OK] Correct: Each bit operation is fast, but if you check every bit one by one, the total time depends on how many bits there are.
Understanding bit manipulation time helps you explain why some solutions are fast and others slow, a useful skill in interviews.
"What if we used a built-in function that counts bits in constant time? How would the time complexity change?"