Binary Counter Exhibit

Easybit manipulationAlso known as Counting Bits

A science museum has a wall of bulbs that counts in binary, one number per second: 0, 1, 10, 11, 100, and so on, with a lit bulb for every 1 bit.

To plan the power supply for a show counting from 0 up to n, the electrician needs the number of lit bulbs at each number.

Your task

Write litBulbs(n). Return a list of length n + 1 where position i holds the number of 1 bits in the binary form of i.

Aim for O(n) total time: build each count from one you already have instead of examining every bit of every number.

litBulbs(n: int) → int[]

Examples

Example 1
Input
n = 5
Output
[0, 1, 1, 2, 1, 2]
Why

0 = 0, 1 = 1, 2 = 10, 3 = 11, 4 = 100, 5 = 101. Counting the 1s gives 0, 1, 1, 2, 1, 2.

Example 2
Input
n = 8
Output
[0, 1, 1, 2, 1, 2, 2, 3, 1]
Why

The count drops back to 1 at 4 and at 8: each power of two lights one bulb, right after a number with many (7 = 111 has three).

Constraints

  • 0 ≤ n ≤ 100,000
Start with brute force

For each number from 0 to n, count its 1 bits one at a time: check the last bit, shift right, repeat until 0.

That is up to about 17 steps per number when n is 100,000, so O(n log n). That is not slow, but it repeats work, because the count for 12 already contains the count for 6, which was computed a moment ago.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code