Start learning free

LESSON 589 OF 671 · BIT MANIPULATION

Counting Bits in Java: O(n) with Dynamic Programming

Practice O(n) Read the full explanation

You get a whole number n.

Return an array bits with n + 1 numbers. For each i, bits[i] is how many 1s the number i has in binary.

 

Example 1:

Input: n = 4
Output: [0,1,1,2,1]
Explanation: Each number in binary:
0 is 0, with no 1s.
1 is 1, with one 1.
2 is 10, with one 1.
3 is 11, with two 1s.
4 is 100, with one 1.

Example 2:

Input: n = 8
Output: [0,1,1,2,1,2,2,3,1]
Explanation: 7 is 111 in binary, so it has three 1s.
8 is 1000, so it has one 1.

Example 3:

Input: n = 0
Output: [0]
Explanation: The only number is 0, and it has no 1s.

 

Constraints:

  • n is from 0 to 100,000.
Note:

Your algorithm should run in O(n) time, a constant amount of work per number, and use O(1) extra space besides the array it returns.



Shifting a number one place to the right drops its last bit: 13 is 1101, and 13 shifted right is 110, which is 6. So 13 has the 1 bits of 6, plus its own last bit.

Fill the answer from 0 up to n. When you reach i, the count of i shifted right by one is already in the array, because that number is smaller than i. Add the last bit of i, which is i AND 1: 1 when i is odd, 0 when it is even.

Each number from 1 to n takes one step: O(n) time.
Apart from the array we return, we keep only the loop variable, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · BIT MANIPULATION

    Counting Bits in Java, explained

    Problem overview

    The method countBits(int n) returns an int[] of n + 1 numbers. Entry i is the number of 1 bits in the binary form of i, for every i from 0 to n.

    For n = 5 the numbers 0 to 5 are 0, 1, 10, 11, 100 and 101 in binary, so the result is [0, 1, 1, 2, 1, 2]. For n = 0 the result is [0].

    The target is O(n) time, a constant amount of work per number, and no extra space beyond the returned array.

    Approach: reuse the answer of a smaller number

    Counting the bits of every number separately costs up to about 17 steps each for numbers up to 100,000. A faster way notices that the answers are related.

    Shifting a number right by one, i >> 1, drops its last bit. The result is smaller than i (for i >= 1), so its bit count is already in the array if we fill it from the start. The number i itself has the same bits plus that last one, and the last bit is i & 1: 1 when i is odd and 0 when it is even. So:

    bits[i] = bits[i >> 1] + (i & 1)
    

    Take 13, which is 1101. Shifted right it is 110, which is 6 and has two 1 bits. The last bit of 13 is 1, so 13 has three. This is dynamic programming: each answer is built from an answer already stored.

    For n = 5 the loop does this:

    1 -> bits[0]=0 + 1 = 1
    2 -> bits[1]=1 + 0 = 1
    3 -> bits[1]=1 + 1 = 2
    4 -> bits[2]=1 + 0 = 1
    5 -> bits[2]=1 + 1 = 2
    

    Step by step

    1. Create bits, an int[] of size n + 1. Java fills a new int array with zeros, and 0 has no 1 bits, so bits[0] is already right.
    2. Loop i from 1 up to and including n. Counting upward matters: each number reads the entry of a smaller one, which must already be filled.
    3. Apply the rule: bits[i] = bits[i >> 1] + (i & 1).
    4. Return bits.

    The solution in Java

    class Solution {
        public int[] countBits(int n) {
            int[] bits = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                bits[i] = bits[i >> 1] + (i & 1);
            }
            return bits;
        }
    }
    

    The Java details worth a closer look:

    • Keep the parentheses around i & 1. Without them bits[i >> 1] + i & 1 is read as (bits[i >> 1] + i) & 1, because + binds tighter than &. That is a different number, and wrong.
    • Array size. The array has n + 1 entries so that index n exists. The loop's i <= n is the matching bound; i < n would leave the last entry at 0.
    • >> on positive numbers. For non-negative i, i >> 1 is the same as dividing by 2 and dropping the remainder. Since i is never negative here, the sign-copying behaviour of >> doesn't come into play.
    • Indexing with an expression. bits[i >> 1] uses the shift result directly as an index. No cast is needed because it is already an int.

    Complexity

    Time: O(n). Each of the n iterations does one shift, one AND, one addition and one array read and write.

    Space: O(1) extra. The only memory is the returned array of n + 1 numbers, which the task requires anyway.

    Edge cases and common mistakes

    • n = 0. The array has one entry, the loop starts at 1 and doesn't run, and the result is [0].
    • Starting the loop at 0. Not harmful here: bits[0 >> 1] + (0 & 1) is bits[0] + 0. Starting at 1 just skips a pointless step.
    • Counting downward. A loop from n to 1 would read entries that haven't been filled yet, and they would still be 0.
    • Dropping the parentheses. This is the classic slip, and it gives wrong values without any error message.
    • Off by one in the size. new int[n] makes index n invalid, and the loop throws an ArrayIndexOutOfBoundsException when it reaches it.

    Testing

    • n = 0 gives [0].
    • n = 2 gives [0, 1, 1].
    • n = 5 gives [0, 1, 1, 2, 1, 2].
    • n = 13 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free