0:00 / 0:00

Count the ones in every number from 0 to n. Each answer is the count for i shifted right one bit, plus its last bit.

▼

The problem

LeetCode 338 (Easy). Given an integer n, return a list ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.

Example (LeetCode's second): n = 5 → [0, 1, 1, 2, 1, 2].

def countBits(n):
    ans = [0] * (n + 1)
    for i in range(1, n + 1):
        ans[i] = ans[i >> 1] + (i & 1)
    return ans
TRY IT ON LEETCODE ▶

The solution

def countBits(n):
    ans = [0] * (n + 1)
    for i in range(1, n + 1):
        ans[i] = ans[i >> 1] + (i & 1)
    return ans

Transcript

Counting Bits. You get a number n. Return a list with one entry for every i from zero to n, where entry i is how many one bits i has in binary.

Take n equals five. Zero has no ones at all. One, two and four each have a single one. Three is one one, and five is one zero one, so they get two each. The answer is zero, one, one, two, one, two.

The simple way counts every number on its own, digit by digit. Thirteen is one one zero one: four digits to read, three ones. A number up to n has about log n digits, so that's n log n steps in all, and no count is ever reused.

But a smaller number already holds most of the answer. Shift thirteen right by one, and its last digit falls off. What's left is one one zero, which is six: half of thirteen, rounded down. Six comes before thirteen, so its row is already built. Copy its two beads, then add back the bit that fell off. It was a one, so thirteen gets three.

The code is one loop. Start with a list of zeros. For each i from one to n, entry i is the entry for i shifted right by one, plus i AND one, the bit that fell off. Half of i is always smaller than i, so that entry is always ready.

Let's build the rack up to eight. One copies zero, plus a bead. Two copies one, and it's even, so nothing more. Three copies one, plus a bead. Four copies two. Five copies two, plus one. Six copies three. Seven copies three, plus one: three beads. Eight copies four: just one bead.

Each entry is one lookup and one add, so the time is O of n, with no digit counting at all. Besides the answer list itself, the extra space is constant.

Drop the last bit, copy the smaller row, add the bit back. That's Counting Bits.