Counting Bits solution explained

The Counting Bits solution builds the answer list from left to right with one rule: the count for i equals the count for i >> 1 plus the last bit of i. Every number reuses the answer for a smaller number that is already in the list, so the whole list for 0 to n takes O(n) time instead of counting each number's bits separately.

By Published 6 min read

The problem in plain words

You are given a non-negative whole number n. Produce a list of n + 1 entries where entry i holds the number of 1 bits in the binary form of i. So the list always starts with the answer for 0, which is 0, and ends with the answer for n.

The list for n = 9, computed by the code on this page
iBinaryOnesReused from
000starting value
111counts[0] + 1
2101counts[1] + 0
3112counts[1] + 1
41001counts[2] + 0
51012counts[2] + 1
61102counts[3] + 0
71113counts[3] + 1
810001counts[4] + 0
910012counts[4] + 1
The list for n = 9, computed by the code on this page. Scroll sideways on a small screen.

The full answer for n = 9 is [0, 1, 1, 2, 1, 2, 2, 3, 1, 2]. For n = 0 it is simply [0].

What the interviewer is looking for

Counting bits for one number is a warm-up. Asking for all of them is a test of whether you notice that the work overlaps. The numbers 6 and 3 differ only by a trailing zero, so once you know 3 has two ones, 6 must too. Spotting that link and turning it into a recurrence is a small, clean dynamic programming step, and it is often the reason this problem appears in a screen. Interviewers will usually ask you to state the complexity of both versions and to justify the recurrence in a sentence.

Follow-up questions

  • Use a different recurrence. Removing the lowest 1 bit also gives a smaller number: counts[i] = counts[i & (i - 1)] + 1. Both are O(n).
  • Can you do it without any bit operators? Yes: counts[i] = counts[i // 2] + i % 2 is the same rule in arithmetic.
  • What about a range from a to b? Compute the prefix up to b and keep the slice, or count each with a popcount if the range is small and far from zero.
  • Total ones from 0 to n, not the list. That has a pattern by bit position and can be done in O(log n); a good stretch question.
  • Memory. The output itself is O(n); nothing else beyond it is needed.

A first answer: count each number separately

Loop from 0 to n, and for each number shift it right until it reaches zero, adding the last bit each time. A number i has about log2(i) bits, so the total work is O(n log n). It is correct and a good opening line, especially if you then point out that it repeats work: counting 12 redoes everything you already did for 6 and for 3.

def bit_counts_slow(n):
    result = []
    for i in range(n + 1):
        ones, x = 0, i
        while x:
            ones += x & 1
            x >>= 1
        result.append(ones)
    return result
Count each number on its own: O(n log n) time.

The fast answer: reuse half of each number

Shifting i right by one drops its last binary digit. The result, i >> 1, is smaller than i, so its count is already in the list. The only bit that was lost is the last one, which is i & 1. So the count for i is the count for i >> 1 plus that last bit. Fill the list from 1 upward and every lookup points backwards to an entry that is already filled.

def bit_counts(n):
    counts = [0] * (n + 1)
    for i in range(1, n + 1):
        # i >> 1 drops the last bit; (i & 1) adds it back if it was a 1
        counts[i] = counts[i >> 1] + (i & 1)
    return counts
Python: one lookup and one add per number. O(n) time, O(1) extra beyond the output.
function bitCounts(n) {
  const counts = new Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) {
    counts[i] = counts[i >> 1] + (i & 1);
  }
  return counts;
}
JavaScript: the same recurrence with a preallocated array.

The second recurrence is just as short. It relies on the same identity used in Number of 1 Bits: i & (i - 1) is i with its lowest 1 bit erased. That number is smaller and has exactly one fewer 1, so add one to its count.

def bit_counts_lowbit(n):
    counts = [0] * (n + 1)
    for i in range(1, n + 1):
        counts[i] = counts[i & (i - 1)] + 1  # i with its lowest 1 bit erased
    return counts
The lowest-bit recurrence: also O(n).

Cost of each approach

Time and extra memory for the list from 0 to n
ApproachTimeExtra memoryNotes
Count each number's bitsO(n log n)O(1) beyond the outputEasy first answer; repeats work
Built-in popcount per numberO(n) callsO(1) beyond the outputFast in practice; dodges the point of the question
counts[i >> 1] + (i & 1)O(n)O(1) beyond the outputThe expected answer
counts[i & (i - 1)] + 1O(n)O(1) beyond the outputSame cost, different smaller subproblem
Time and extra memory for the list from 0 to n. Scroll sideways on a small screen.

Edge cases

  • n = 0: return [0], a list of length one, not an empty list.
  • n = 1: [0, 1]. Off-by-one errors in the loop bounds show up here.
  • Powers of two such as 8 or 1024: exactly one 1 bit. A quick sanity check while tracing.
  • Numbers of the form 2^k - 1 such as 7 or 255: all ones, the largest counts in their range.
  • Large n: the list itself dominates memory. Ask about limits if n could be in the hundreds of millions.

Common slips

  • Creating a list of length n instead of n + 1, so the answer for n is missing.
  • Starting the loop at 0 and computing counts[0] from counts[0], which is harmless here but signals that the base case was not thought about.
  • Writing i >> 1 + (i & 1) in a language where + binds tighter than >>, which shifts by the wrong amount. Use parentheses.
  • Calling a built-in popcount in a loop and calling it dynamic programming.
  • Describing the recurrence without saying why i >> 1 is always already computed: it is smaller than i.

How to explain it out loud

Fictional example

Talking through the recurrence
Candidate
I could count bits for each number from scratch, which is n times about log n. But the numbers overlap a lot.
Candidate
If I shift i right by one, I get a smaller number with the same bits except the last one. That smaller number's count is already in my list.
Candidate
So counts of i is counts of i shifted right, plus i AND 1. I fill the list from 1 up to n, one constant-time step each, so it's linear time, and nothing extra besides the output.

Start with Number of 1 Bits if the n & (n - 1) identity is new. Reverse Bits practices the same shifts in a different direction, and Sum of Two Integers builds addition itself out of XOR, AND and shifts.

Rehearsing it with Natively

When you practice, Natively can take a screenshot of the prompt on your screen, on Mac or Windows, and help you find the reuse that turns this into a linear-time answer, or check your loop bounds when the list comes out one short. Because it keeps a transcript of the mock session, you can reread whether you actually explained why the smaller entry is always ready.

Questions people ask

How do you solve Counting Bits in O(n)?

Fill a list from 0 to n with counts[i] = counts[i >> 1] + (i & 1). Shifting right drops the last bit and gives a smaller number whose count is already known; the last bit is added back.

Is Counting Bits a dynamic programming problem?

Yes. Each answer is built from the answer to a smaller subproblem, either i >> 1 or i & (i - 1), that has already been computed.

What is the time complexity of counting bits for each number separately?

O(n log n), because each number i has about log2(i) bits to inspect. The recurrence brings it down to O(n).

What should Counting Bits return for n = 0?

A list with one entry, [0], because the list covers every number from 0 to n inclusive.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP