Counting Bits

25 min · countBits()

One answer can unlock the next. If you already know the bit count for 6, you can use it to find the bit count for 12 without inspecting 12 from scratch.

Given a non-negative integer n, return an array ans with one entry for every integer from 0 through n. A set bit is a binary digit equal to 1; ans[i] must contain the number of set bits in i.

A few ground rules:

  • The returned array has exactly n + 1 entries.
  • Index i stores the answer for the integer i.
  • Zero has no set bits, so ans[0] is always 0.

Constraints

  • 0 <= n <= 100_000

Hints

Start one number at a time

You can count a number's 1 digits by repeatedly checking its last binary digit, then shifting the number right. Doing that for every value gives you a solid first solution.

Remove the last binary digit

Shifting i right once produces i >> 1. You've already computed that smaller number's answer by the time you reach i.

Write the reuse rule

The dropped digit is i & 1, either 0 or 1. Combine both observations: ans[i] = ans[i >> 1] + (i & 1).

Follow-up

Can you produce every answer in one pass without converting any number to a binary string?

Visible cases

Examples

Example 1

ready
Input
n = 2
Expected
[
  0,
  1,
  1
]
Why
0, 1, and 2 have 0, 1, and 1 set bits

Example 2

ready
Input
n = 5
Expected
[
  0,
  1,
  1,
  2,
  1,
  2
]
Why
the result records every bit count from 0 through 5

Example 3

ready
Input
n = 8
Expected
[
  0,
  1,
  1,
  2,
  1,
  2,
  2,
  3,
  1
]
Why
8 is a power of two, so it has one set bit

Interview signal

Asked at

AmazonApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite