Algo-Sim › Matrix & Bit Manipulation
Counting Bits
Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Set-bit counts for every number 0..n in O(n): dp[i] = dp[i >> 1] + (i & 1) reuses the count of i without its last bit.
Problem
Given n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.
Constraints
- 0 ≤ n ≤ 10⁵
- Follow-up: O(n) total, without a built-in popcount
Edge cases to test
- n = 0:
[0] - Powers of two
- n = 1
Follow-up questions
- Is there another recurrence?
dp[i] = dp[i & (i − 1)] + 1: drop the lowest set bit instead of the last bit. Same O(n).- Why is this better than calling popcount n times?
- Popcount loops cost O(log n) each without hardware support; the DP reuses earlier answers for O(1) each.
Solution
Java
public int[] countBits(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = dp[i >> 1] + (i & 1);
}
return dp;
}Python
def count_bits(n):
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dpC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> countBits(int n) {
vector<int> dp = vector<int>(n + 1);
for (int i = 1; i <= n; i++) {
dp[i] = dp[i >> 1] + (i & 1);
}
return dp;
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)