Search⌘ K
AI Features

Counting Bits

Understand how to implement a dynamic programming approach to count the number of set bits in the binary representation of integers up to n. Explore memoization and tabulation to optimize your solution for improved performance and practice coding this problem hands-on.

Statement

For a given positive integer, n, your task is to return an array of length n+1n+1 such that for each xx where 0xn0 \leq x \leq n, result[x] is the count of 11s in the binary representation of xx.

Constraints:

  • 0n1040 \leq n \leq 10^4

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Counting Bits

1.

What will be the output if n=6n = 6?

A.

[0,1,1,2,1,2,2][0, 1, 1, 2, 1, 2, 2]

B.

[0,1,1,2,1,1,2][0, 1, 1, 2, 1, 1, 2]

C.

[0,1,2,2,1,2,1][0, 1, 2, 2, 1, 2, 1]


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > CountBits.java
import java.util.*;
public class CountBits {
public static int[] countingBits(int n) {
// Replace this placeholder return statement with your code
return new int[]{};
}
}
Counting Bits