Counting Bits — Solution in Python, Java & C++
Counting Bits solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon and Google.
Counting Bits is an easy coding problem on dynamic programming and bit manipulation, asked in Amazon, Google, Meta and Apple interviews.
- Difficulty: Easy
- Topics: Dynamic Programming, Bit Manipulation
- Asked at: Amazon, Google, Meta, Apple, MathWorks
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer n, return an array out of length n + 1 where out[i] is the number of 1 bits in the binary representation of i.
Example 1
Input: n = 2
Output: [0,1,1]
Example 2
Input: n = 5
Output: [0,1,1,2,1,2]
Example 3
Input: n = 0
Output: [0]
Constraints
0 <= n <= 40
Follow-up: Can you do it in a single pass, in O(n) time and without any built-in popcount?
Hints for Counting Bits
Hint 1
Counting the bits of every number independently is O(n log n) — you can do better.
Hint 2
iandi >> 1differ only by the lowest bit ofi.Hint 3
So
out[i] = out[i >> 1] + (i & 1), filling the array left to right.
How to solve Counting Bits
i and i >> 1 differ only in the lowest bit, so out[i] = out[i >> 1] + (i & 1).
Approach
- Set
out[0] = 0. - For
ifrom 1 ton,out[i] = out[i >> 1] + (i & 1).
Why it works
Shifting right drops the lowest bit, whose value is i & 1; the rest of the popcount was already computed for a smaller index.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
out[i] = out[i & (i - 1)] + 1is the equivalent recurrence via the lowest set bit.
Reference solution
Python
def countBits(n: int):
out = [0] * (n + 1)
for i in range(1, n + 1):
out[i] = out[i >> 1] + (i & 1)
return outJava
public static int[] countBits(int n) {
int[] out = new int[n + 1];
for (int i = 1; i <= n; i++) out[i] = out[i >> 1] + (i & 1);
return out;
}C++
vector<int> countBits(int n) {
vector<int> out(n + 1, 0);
for (int i = 1; i <= n; i++) out[i] = out[i >> 1] + (i & 1);
return out;
}JavaScript
var countBits = function(n) {
const out = [0];
for (let i = 1; i <= n; i++) out.push(out[i >> 1] + (i & 1));
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 402 dynamic programming problems · the whole catalogue
Learn the technique: Dynamic Programming · Bit Manipulation