EasyDynamic Programming · Bit Manipulation

Counting Bits

Given an integer n, return an array output of length n + 1 where output[i] is the number of 1 bits in the binary representation of i, for every i from 0 to n.

n = 4 → [0,1,1,2,1]0→0, 1→1, 2→10, 3→11, 4→100

Try:
CALL
1 / 1

Code

The highlighted line runs next. The pill shows the live values in the running call.

Variables

The data structures the code is building

Output array

Each cell: i, its binary form, and its bit count

Time and space complexity

Answers for 0 … n; extra space does not count the output array. The highlighted row is the solution being traced.

Keyboard: ← → step, Space play or pause. n from 0 to 63 (the problem allows up to 1000).