Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in Go: Dynamic Programming with a Shift

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

    GO · BIT MANIPULATION

    Counting Bits in Go, explained

    Problem overview

    The function countBits receives an integer n and returns a slice of n + 1 numbers. Entry i of that slice 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 answer is [0 1 1 2 1 2]. For n = 2 it is [0 1 1], and for n = 0 it is [0].

    The lesson asks for O(n) time, a constant amount of work per number, and no extra space besides the slice that is returned.

    Approach: reuse the answer for a smaller number

    Counting the bits of every number separately would take several steps per number. The faster idea is that each answer can be built from one you already have.

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

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

    Here i >> 1 is i without its last bit, and i & 1 is that last bit: 1 when i is odd and 0 when it is even. Because i >> 1 is smaller than i, its answer is already in the slice when we reach i, as long as we fill the slice from small numbers to large ones. This is a small piece of dynamic programming: each answer is computed once from an earlier one.

    The starting point is bits[0]. The number 0 has no 1 bits, and a new slice made by make is filled with zeros, so that entry is already right.

    For n = 13 the function produces:

    [0 1 1 2 1 2 2 3 1 2 2 3 2 3]

    The last entry is 3, matching the three 1 bits of 1101.

    Step by step

    1. Create bits with make([]int, n+1). It holds n + 1 zeros, one for each number from 0 to n.
    2. Loop from 1 to n inclusive: i starts at 1 because bits[0] is already correct, and the condition is i <= n so the last number is included. Counting upward matters, since each step reads a smaller index.
    3. Fill the entry with bits[i>>1] + (i & 1). The parentheses around i & 1 are not required here, but they make the two parts easy to read.
    4. Return bits after the loop.

    The solution in Go

    func countBits(n int) []int {
        bits := make([]int, n+1)
        for i := 1; i <= n; i++ {
            bits[i] = bits[i>>1] + (i & 1)
        }
        return bits
    }
    

    The Go details worth knowing:

    • make([]int, n+1) creates a slice of length n + 1 with every element set to 0. Go zeroes new memory, so no loop is needed to initialise it.
    • Precedence. In Go, >> and & bind tighter than +, so the code means what it looks like even without the parentheses.

    Complexity

    Time: O(n). The loop runs n times and each pass does one shift, one AND, one addition and one assignment.

    Space: O(1) extra. The only memory that grows with n is the slice we have to return. Apart from it, the function keeps the loop variable.

    Edge cases and common mistakes

    • n = 0. The slice has one element, the loop does not run, and the result is [0].
    • Allocating n instead of n + 1. The slice needs an entry for n itself. With length n, the last write would be out of range and the program would panic.
    • Using i < n. That loop stops one number early and leaves the last entry at 0.
    • Looping downward. The entry bits[i>>1] would not be filled in yet, and the counts would be wrong.
    • Counting bits one by one for each number. It gives the right answer, but it repeats work the shift makes unnecessary.

    Testing

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