PracticeNeetCode ↗LeetCode ↗
Given an integer n, return an array ans of length n + 1 where ans[i] is the number of 1-bits in the binary representation of i, for every i from 0 to n.
i is wasteful — reuse work already done for smaller numbers.i (i >> 1) gives a smaller number whose bit count is already in the array.i & 1 — add it back to get i's full count.ans as an array of n + 1 zeros.i from 1 to n: set ans[i] = ans[i >> 1] + (i & 1).i >> 1 is always smaller than i, so its answer is already filled in by the time you reach i.ans once every index is filled.Time: O(n) — Space: O(n) for the output (O(1) extra)
def countBits(n: int) -> list[int]:
ans = [0] * (n + 1)
for i in range(1, n + 1):
ans[i] = ans[i >> 1] + (i & 1)
return ansHow the solution above works, piece by piece.
i >> 1 is i without its last bit, a smaller number whose answer is already computed.i & 1 is that last bit (1 if i is odd).ans[i] = ans[i >> 1] + (i & 1): the bits of the shorter number plus the dropped bit.Running it on n = 5: