338. Counting Bits
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Bit Manipulation
- Time
- O(N)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven a non-negative integer n, return an array of length n+1 where each element at index i holds the number of 1-bits in the binary representation of i.
Approach
- Use dynamic programming: the popcount of i equals the popcount of i right-shifted by one (i.e.,
i/2) plus the least-significant bit of i (i & 1). - This works because dropping the last bit gives a smaller number already in the table, and we only need to add back whether that dropped bit was set.
- A single left-to-right pass fills the table in O(n) time with no calls to any library bit-count function.
#include <vector>
using namespace std;
class Solution {
public:
vector<int> countBits(int n) {
vector<int> dp(n + 1, 0);
// dp[i] = dp[i >> 1] + (i & 1)
// "shift right" gives a previously computed value;
// add 1 if the original LSB was set.
for (int i = 1; i <= n; ++i) {
dp[i] = dp[i >> 1] + (i & 1);
}
return dp;
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n+1);
// use bottom-up dynamic programming
ans[0]=0;
for(int i=1; i<=n; ++i){
ans[i]=ans[i>>1]+(i&1);
}
return ans;
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) Time O(N) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.