Counting Bits
Easy · Bit Manipulation · Explanation and code example
Bit Manipulation (Optimal)
How it works
We want to find the number of set bits (1s) in every number from 0 to n.
A very important observation from binary representation is:
- Right-shifting a number by 1 (
i >> 1) removes the least significant bit (i & 1)tells us whether the last bit ofiis1or0
So, the number of set bits in i can be built from a smaller number:
setBits(i) = setBits(i >> 1) + (i & 1)
This means each result depends only on a previously computed value, making it a perfect fit for Dynamic Programming.
Steps
- Create a DP array
dpof sizen + 1dp[i]stores the number of set bits ini
- Initialize
dp[0] = 0 - For every number
ifrom1ton:- Right shift
iby 1 to geti >> 1 - Check the last bit using
(i & 1) - Compute:
- Right shift
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)extra space.O(n)space for the output array.
Things to watch for
Incorrect Bit Shift Operator
When using the DP recurrence dp[i] = dp[i >> 1] + (i & 1), a common mistake is using left shift instead of right shift, or confusing the operator precedence.
Off-by-One in Loop Bounds
The problem asks for bits count from 0 to n inclusive, meaning the result array should have n + 1 elements. A common mistake is creating an array of size n or iterating up to n - 1.
Python code example
from typing import List
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for i in range(n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dp
C++ code example
class Solution {
public:
vector<int> countBits(int n) {
vector<int> dp(n + 1);
for (int i = 1; i <= n; i++) {
dp[i] = dp[i >> 1] + (i & 1);
}
return dp;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.