Coding · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Counting Bits
Problem
Given a non-negative integer n, produce an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary representation of i, for every i from 0 to n.
nis at most a couple hundred thousand.- The intended solution runs in a single linear pass without calling a popcount routine on each number.
Examples
n = 3→[0, 1, 1, 2]:0 = 0b0,1 = 0b1,2 = 0b10,3 = 0b11.n = 7→[0, 1, 1, 2, 1, 2, 2, 3]:5 = 0b101has two bits,6 = 0b110has two,7 = 0b111has three.n = 0→[0].
Hints
- Computing popcount independently for each number costs O(n log n). Can the answer for
ibe derived from an answer you already have? - What is the relationship between the bits of
iand the bits ofi >> 1? What aboutiandi & (i - 1)? - Dynamic programming:
ans[i] = ans[i >> 1] + (i & 1), or equivalentlyans[i] = ans[i & (i - 1)] + 1.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.