15% off all plans & roadmaps Use code
See plansCounting Bits
- LeetCode 338
- Easy
- Bit Manipulation Patterns
- Bitwise DP - Counting Bits Optimization
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
nis 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 + 1entries, so any solution needs at least O(n) time and O(n) space for the answer itself. Linear time is the best possible. ncan 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.
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.
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
- Create
answithn + 1zeros. - For each
ifrom 0 ton, copy it into a working variablexand setcount = 0. - While
x > 0, addx & 1tocount, then shiftxright by one. - Store
countinans[i]. - Return
ans.
Dry run
Run the inner loop on i = 13, binary 1101:
| x (binary) | x & 1 | count after |
|---|---|---|
| 1101 | 1 | 1 |
| 110 | 0 | 1 |
| 11 | 1 | 2 |
| 1 | 1 | 3 |
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
| Time | O(n log n) |
|---|---|
| Space | O(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 ansJavaTested in our runner
import java.util.*;
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) {
int x = i;
int count = 0;
while (x > 0) {
count += x & 1; // add the lowest bit
x >>= 1; // drop the lowest bit
}
ans[i] = count;
}
return ans;
}
}C++Tested in our runner
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1, 0);
for (int i = 0; i <= n; i++) {
int x = i;
int count = 0;
while (x > 0) {
count += x & 1; // add the lowest bit
x >>= 1; // drop the lowest bit
}
ans[i] = count;
}
return ans;
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number[]}
*/
var countBits = function(n) {
const ans = new Array(n + 1).fill(0);
for (let i = 0; i <= n; i++) {
let x = i;
let count = 0;
while (x > 0) {
count += x & 1; // add the lowest bit
x >>= 1; // drop the lowest bit
}
ans[i] = count;
}
return ans;
};GoTested in our runner
func countBits(n int) []int {
ans := make([]int, n+1)
for i := 0; i <= n; i++ {
x := i
count := 0
for x > 0 {
count += x & 1 // add the lowest bit
x >>= 1 // drop the lowest bit
}
ans[i] = count
}
return ans
}C#Tested in our runner
public class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) {
int x = i;
int 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
- Create
answithn + 1zeros. - For each
ifrom 1 ton, setx = iandcount = 0. - While
x != 0, replacexwithx & (x - 1)and add 1 tocount. - Store
countinans[i]. - Return
ans.
Dry run
Run the inner loop on i = 13, binary 1101:
| x before | x - 1 | x & (x - 1) | count after |
|---|---|---|---|
| 1101 | 1100 | 1100 | 1 |
| 1100 | 1011 | 1000 | 2 |
| 1000 | 0111 | 0000 | 3 |
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
| Time | O(n log n) |
|---|---|
| Space | O(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 ansJavaTested in our runner
import java.util.*;
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 1; i <= n; i++) {
int x = i;
int count = 0;
while (x != 0) {
x &= x - 1; // clear the lowest set bit
count++;
}
ans[i] = count;
}
return ans;
}
}C++Tested in our runner
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1, 0);
for (int i = 1; i <= n; i++) {
int x = i;
int count = 0;
while (x != 0) {
x &= x - 1; // clear the lowest set bit
count++;
}
ans[i] = count;
}
return ans;
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number[]}
*/
var countBits = function(n) {
const ans = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
let x = i;
let count = 0;
while (x !== 0) {
x &= x - 1; // clear the lowest set bit
count++;
}
ans[i] = count;
}
return ans;
};GoTested in our runner
func countBits(n int) []int {
ans := make([]int, n+1)
for i := 1; i <= n; i++ {
x := i
count := 0
for x != 0 {
x &= x - 1 // clear the lowest set bit
count++
}
ans[i] = count
}
return ans
}C#Tested in our runner
public class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 1; i <= n; i++) {
int x = i;
int count = 0;
while (x != 0) {
x &= x - 1; // clear the lowest set bit
count++;
}
ans[i] = count;
}
return ans;
}
}
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
- Create
answithn + 1zeros. Index 0 stays 0 because zero has no set bits. - Loop
ifrom 1 ton. - Read
ans[i >> 1], the count foriwith its last bit removed. - Add
i & 1, which is 1 for oddiand 0 for eveni. - Write the sum into
ans[i]. - Return
ans.
Dry run
Trace for n = 15. The table shows the lookup index, the low bit, and the value written.
| i | binary | i >> 1 | ans[i >> 1] | i & 1 | ans[i] |
|---|---|---|---|---|---|
| 0 | 0000 | base | base | base | 0 |
| 1 | 0001 | 0 | 0 | 1 | 1 |
| 2 | 0010 | 1 | 1 | 0 | 1 |
| 3 | 0011 | 1 | 1 | 1 | 2 |
| 4 | 0100 | 2 | 1 | 0 | 1 |
| 5 | 0101 | 2 | 1 | 1 | 2 |
| 6 | 0110 | 3 | 2 | 0 | 2 |
| 7 | 0111 | 3 | 2 | 1 | 3 |
| 8 | 1000 | 4 | 1 | 0 | 1 |
| 9 | 1001 | 4 | 1 | 1 | 2 |
| 10 | 1010 | 5 | 2 | 0 | 2 |
| 11 | 1011 | 5 | 2 | 1 | 3 |
| 12 | 1100 | 6 | 2 | 0 | 2 |
| 13 | 1101 | 6 | 2 | 1 | 3 |
| 14 | 1110 | 7 | 3 | 0 | 3 |
| 15 | 1111 | 7 | 3 | 1 | 4 |
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
| Time | O(n) |
|---|---|
| Space | O(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 ansJavaTested in our runner
import java.util.*;
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 1; i <= n; i++) {
// bits of i = bits of (i >> 1) plus the lowest bit
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
}C++Tested in our runner
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1, 0);
for (int i = 1; i <= n; i++) {
// bits of i = bits of (i >> 1) plus the lowest bit
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number[]}
*/
var countBits = function(n) {
const ans = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
// bits of i = bits of (i >> 1) plus the lowest bit
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
};GoTested in our runner
func countBits(n int) []int {
ans := make([]int, n+1)
for i := 1; i <= n; i++ {
// bits of i = bits of (i >> 1) plus the lowest bit
ans[i] = ans[i>>1] + (i & 1)
}
return ans
}C#Tested in our runner
public class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 1; i <= n; i++) {
// 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] * ninstead of[0] * (n + 1). The range 0 to n has n + 1 values, so writingans[n]goes out of bounds. Size the arrayn + 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. Useans[i >> 1] + (i & 1), orans[i & (i - 1)] + 1. - Forgetting the
+ (i & 1)term and writingans[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 >> 2ori << 1for the lookup. A left shift gives a larger index that is not filled yet. Shift right by exactly one so the index is smaller thaniand already computed. - Calling a built-in such as
bin(i).count('1'),Integer.bitCountor__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 thatans[0]must be 0 is not. If you build the array with a method that leaves garbage in it, setans[0] = 0yourself.
Edge cases
n = 0returns[0]. The loop from 1 to 0 does nothing, so the zero-filled array is already the answer.n = 1returns[0, 1]. The only iteration readsans[0]and adds the low bit 1.nis 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.nis 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]equalsans[k], andans[2k + 1]equalsans[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 - 1also 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)] + 1works fori >= 1. A third form uses the highest power of two. Ifpis the largest power of two not abovei, thenans[i] = ans[i - p] + 1. All three fill the table in one pass, and thei >> 1form 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
Related problems
- Parallel Courses · same technique: Bitwise DP - Counting Bits Optimization
- Single Number · same pattern: Bit Manipulation Patterns
- Missing Number · same pattern: Bit Manipulation Patterns
- Reverse Bits · same pattern: Bit Manipulation Patterns
- Number of 1 Bits · same pattern: Bit Manipulation Patterns
- Power of Two · same pattern: Bit Manipulation Patterns
- Find the Difference · same pattern: Bit Manipulation Patterns
- Power of Four · same pattern: Bit Manipulation Patterns
- Pow(x, n) · same pattern: Bit Manipulation Patterns
- Sum of Two Integers · same pattern: Bit Manipulation Patterns