15% off all plans & roadmaps Use code

See plans

Counting Bits

Updated

TL;DR: Return an array where entry i is the number of 1 bits in i, for every i from 0 to n. Each count equals the count for i >> 1 plus the lowest bit of i, so one left-to-right pass fills the array in O(n).

Problem

Given an integer n, return an array ans of length n + 1 such that for every i with 0 <= i <= n, ans[i] is the number of 1 bits in the binary representation of i.

Example 1

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2

Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Constraints

  • 0 <= n <= 10^5

Constraints that matter

  • n is at most 10^5, so even O(n log n) runs in a few million steps. The limit does not force the linear solution. The problem asks for it anyway, and interviewers expect it.
  • The output has n + 1 entries, so any solution needs at least O(n) time and O(n) space for the answer itself. Linear time is the best possible.
  • n can be 0, so the answer is the single-element array [0]. Your loop must not write to index 1 when the array has length 1.
  • Values stay below 2^17, so the counts are at most 16 and plain 32-bit integers never overflow.

View on LeetCode

Hints

Hint 1

The problem asks for the answer at every index from 0 to n, not for one number.

Hint 2

Treat every number as its own problem.

Solution

Intuition

The problem asks for the answer at every index from 0 to n, not for one number. That wording is the hint. When a problem wants a whole table of results, ask whether each entry can be built from entries you already filled in. This is dynamic programming on bits, often called bitwise DP.

Picture a row of numbered jars where each jar holds how many 1 bits its number has. To fill jar i, you look at jar i shifted down by one bit and add a coin if the dropped bit was 1, so each jar reuses the count already written in an earlier jar instead of recounting from scratch.

Look at how a number relates to a smaller one. Shifting i right by one bit drops the lowest bit and gives i >> 1, which is i // 2. So i is the bits of i >> 1 with one extra bit appended on the right. That extra bit is i & 1.

This gives the recurrence ans[i] = ans[i >> 1] + (i & 1). Take 13, which is 1101. Dropping the last bit gives 110, which is 6, and 6 has two 1 bits. The dropped bit is 1, so 13 has 2 + 1 = 3. Take 12, which is 1100. Dropping the last bit gives 110 again, and the dropped bit is 0, so 12 has 2.

Why is the table always ready when you need it? For every i >= 1, i >> 1 is strictly smaller than i. A left-to-right loop has already filled that index.

Each entry then costs one shift, one AND and one addition, which is constant work.

Watch the pattern animation

Worked example

Input: n = 15
Output: [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
Explanation: The array has 16 entries, one for each number from 0 to 15. Index 7 is 111 so it holds 3, index 8 is 1000 so it holds 1, and index 15 is 1111 so it holds 4. Every entry is the number of 1 bits in its own index.

Approach 1: Brute force: count each number from scratch

Treat every number as its own problem. For each i from 0 to n, test the lowest bit, add it to a counter, shift right, and repeat until the number is 0. Store the counter in ans[i].

This is correct and needs no insight. Say it first in an interview, because it shows you understand what a set bit is.

Steps

  1. Create ans with n + 1 zeros.
  2. For each i from 0 to n, copy it into a working variable x and set count = 0.
  3. While x > 0, add x & 1 to count, then shift x right by one.
  4. Store count in ans[i].
  5. Return ans.

Dry run

Run the inner loop on i = 13, binary 1101:

x (binary)x & 1count after
110111
11001
1112
113

After the last shift x is 0, so the loop stops and ans[13] = 3. The same loop gives 1 for 8, 4 for 15, and 0 for 0. Running it for all 16 numbers produces [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4].

Complexity

TimeO(n log n)
SpaceO(1) extra, O(n) with the output

Here n is the largest number. A number i has about log2(i) + 1 bits, and the inner loop runs once per bit, so the total is the sum over i of log i, which is O(n log n). Only a counter and a copy of i are used besides the output, so extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(n + 1):
            x = i
            count = 0
            while x > 0:
                count += x & 1  # add the lowest bit
                x >>= 1         # drop the lowest bit
            ans[i] = count
        return ans

Approach 2: Brian Kernighan trick per number

What's slow: the brute force loop visits every bit position, including the zeros. A number like 1000000 takes seven iterations to find a single 1 bit.

The insight that fixes it: x & (x - 1) clears the lowest set bit of x. Subtracting 1 flips the lowest 1 to 0 and turns every zero below it into 1, so the AND removes exactly that one bit. Repeat until x is 0, and the number of repeats equals the number of 1 bits. The loop now runs once per set bit, not once per bit position.

Steps

  1. Create ans with n + 1 zeros.
  2. For each i from 1 to n, set x = i and count = 0.
  3. While x != 0, replace x with x & (x - 1) and add 1 to count.
  4. Store count in ans[i].
  5. Return ans.

Dry run

Run the inner loop on i = 13, binary 1101:

x beforex - 1x & (x - 1)count after
1101110011001
1100101110002
1000011100003

The loop ran 3 times because 13 has 3 set bits, so ans[13] = 3. The same loop on 8 runs once and on 15 runs four times. Across all 16 numbers it yields the expected array.

Complexity

TimeO(n log n)
SpaceO(1) extra, O(n) with the output

Here n is the largest number. Each iteration removes one set bit, so a number i needs at most log2(i) + 1 iterations, which happens when every bit is set. Summing over all i still gives O(n log n) in the worst case, although the average work is lower. Space is O(1) beyond the output because only x and count are kept.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(1, n + 1):
            x = i
            count = 0
            while x:
                x &= x - 1  # clear the lowest set bit
                count += 1
            ans[i] = count
        return ans
Bitwise DP - Counting Bits Optimization pattern infographic for Counting Bits

Solution pattern

Bitwise DP - Counting Bits Optimization

Part of Bit Manipulation Patterns

Approach 3: One-pass DP using i >> 1OptimalBitwise DP - Counting Bits Optimization

What's slow: both earlier approaches treat each number as a new problem. The count for 13 is computed again from nothing, even though the count for 6 was already stored two steps earlier in the same table. Every number repeats work that a smaller number already did.

The insight that fixes it: the binary form of i is the binary form of i >> 1 with one extra low bit. So ans[i] = ans[i >> 1] + (i & 1). You read one earlier entry, add the low bit, and write one entry.

There is no inner loop at all. The counts for small numbers feed the counts for larger ones, which is why the pass is linear and needs no built-in popcount.

Why it is correct. Every number i is its prefix i >> 1 with one extra bit appended, so its count of 1 bits is the prefix's count plus that bit. Since i >> 1 is always smaller than i, the loop from left to right has already stored it. The recurrence therefore gives the exact count for every index, with no case skipped.

Steps

  1. Create ans with n + 1 zeros. Index 0 stays 0 because zero has no set bits.
  2. Loop i from 1 to n.
  3. Read ans[i >> 1], the count for i with its last bit removed.
  4. Add i & 1, which is 1 for odd i and 0 for even i.
  5. Write the sum into ans[i].
  6. Return ans.

Dry run

Trace for n = 15. The table shows the lookup index, the low bit, and the value written.

ibinaryi >> 1ans[i >> 1]i & 1ans[i]
00000basebasebase0
100010011
200101101
300111112
401002101
501012112
601103202
701113213
810004101
910014112
1010105202
1110115213
1211006202
1311016213
1411107303
1511117314

Reading the column ans[i] from top to bottom gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4], which matches the expected output.

Complexity

TimeO(n)
SpaceO(1) extra, O(n) with the output

Here n is the input value. The loop body runs n times. Each run does one array read, one shift, one AND, one addition and one array write, all constant time, so the total is O(n).

The only memory is the output array of n + 1 integers, so extra space beyond the answer is O(1). The recurrence is safe because i >> 1 < i for every i >= 1, so each lookup hits an index that is already filled.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(1, n + 1):
            # bits of i = bits of (i >> 1) plus the lowest bit
            ans[i] = ans[i >> 1] + (i & 1)
        return ans

Common mistakes

  • Allocating ans = [0] * n instead of [0] * (n + 1). The range 0 to n has n + 1 values, so writing ans[n] goes out of bounds. Size the array n + 1.
  • Writing ans[i] = ans[i - 1] + 1. Adding one to a number does not add one bit: 7 is 111 and 8 is 1000. Use ans[i >> 1] + (i & 1), or ans[i & (i - 1)] + 1.
  • Forgetting the + (i & 1) term and writing ans[i] = ans[i >> 1]. That is right only for even numbers. Odd numbers end in a 1 bit that the shifted value does not contain, so add it back.
  • Using i >> 2 or i << 1 for the lookup. A left shift gives a larger index that is not filled yet. Shift right by exactly one so the index is smaller than i and already computed.
  • Calling a built-in such as bin(i).count('1'), Integer.bitCount or __builtin_popcount. The result is correct but the follow-up asks you to avoid built-ins, and the interviewer learns nothing about your reasoning.
  • Starting the loop at 0 and reading ans[i >> 1] is harmless, but starting it at 1 and forgetting that ans[0] must be 0 is not. If you build the array with a method that leaves garbage in it, set ans[0] = 0 yourself.

Edge cases

  • n = 0 returns [0]. The loop from 1 to 0 does nothing, so the zero-filled array is already the answer.
  • n = 1 returns [0, 1]. The only iteration reads ans[0] and adds the low bit 1.
  • n is a power of two, such as 8 or 1024. Its entry is 1 because only the top bit is set, and the next entry is 2.
  • n is one less than a power of two, such as 7 or 15. Every bit is set, so the entry equals the bit length: 3 for 7 and 4 for 15.
  • n = 100000. The answer has 100001 entries and the largest count is 16, since 2^16 = 65536 and 100000 is below 2^17. Plain 32-bit integers are enough.
  • Even and odd neighbours. For any even 2k, ans[2k] equals ans[k], and ans[2k + 1] equals ans[k] + 1. Spot-check a few pairs against your output.

Follow-ups interviewers ask

Can you do it in linear time and a single pass?
Yes, and that is the DP approach. Fill the array left to right with ans[i] = ans[i >> 1] + (i & 1). Each entry costs constant work, so the total is O(n) with one pass over the indices.
Can you solve it without a built-in popcount function?
Yes. The DP recurrence uses only a shift, an AND and an addition. The Kernighan loop x &= x - 1 also works without built-ins, but it is O(n log n) in the worst case. I would present the DP version as the answer and mention Kernighan as the stepping stone.
Is there another recurrence that also runs in O(n)?
Yes. Clearing the lowest set bit gives a smaller number, so ans[i] = ans[i & (i - 1)] + 1 works for i >= 1. A third form uses the highest power of two. If p is the largest power of two not above i, then ans[i] = ans[i - p] + 1. All three fill the table in one pass, and the i >> 1 form is the shortest to write and explain.

Counting Bits FAQ

What is the time complexity of Counting Bits?

The optimal solution runs in O(n) time, where n is the input value. The loop makes n iterations and each does constant work. The brute force and Kernighan approaches are O(n log n) in the worst case.

Why use dynamic programming for Counting Bits?

The output needs the bit count of every number from 0 to n, and each count is related to a smaller number's count. Since i >> 1 is the bits of i minus the last one, you can reuse its stored answer. That turns an inner loop of up to 17 steps into a single lookup.

Can Counting Bits be solved in O(1) extra space?

Yes, if you do not count the output. The DP writes straight into the answer array and keeps no other structure, so extra space is O(1). The answer itself has n + 1 entries, so total space including the output is O(n), and no solution can do better.

How do I count bits in binary for one number?

Loop while the number is above 0, add x & 1 to a counter and shift right. Alternatively, repeat x &= x - 1 and count the iterations, which runs once per set bit. Both take O(log x) time for a single number.

What is the Counting Bits answer for n = 5?

It is [0, 1, 1, 2, 1, 2]. The binary forms are 0, 1, 10, 11, 100 and 101, which have 0, 1, 1, 2, 1 and 2 ones. With the DP, ans[5] = ans[2] + 1 = 2.

Why does the Counting Bits recurrence use i >> 1 and not i - 1?

Shifting right removes the last bit, so i differs from i >> 1 by exactly that bit. Subtracting 1 can change many bits at once: 8 is 1000 and 7 is 111. So ans[i - 1] tells you nothing fixed about ans[i].

Asked at

See which companies ask this — Pro

Practise it