TRT
Sign in
easyFoundationsLeetCode#bit manipulation#reuse earlier answers

Counting bits

For every integer from 0 to n, return how many 1 bits it has, in a single pass.

The Runtime Theory Team1 min read
Taught inBits, bytes and number representationEvery value a program stores is a row of bits. How integers are laid out in bytes, how negative numbers work, and why adding 1 can turn a huge number negative.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 2

out[0, 1, 1]

inn = 5

out[0, 1, 1, 2, 1, 2]

inn = 0

out[0]

Given an integer n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i.

Before you code

Counting the bits of every number separately takes about 32 steps per number. You can do it in one step per number by noticing that each number's bits are another, smaller number's bits plus at most one more.

Hints

  1. i >> 1 is i with its lowest bit removed, and it is smaller than i, so its answer is already in the array.
  2. So ans[i] = ans[i >> 1] + (i & 1).
  3. Check it on 5 (101): ans[2] is 1, and the lowest bit of 5 is 1, so ans[5] is 2.

Production & complexity notes

When solving Counting bits on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Bits, bytes and number representation to reinforce the underlying pattern.

What it practices

Shifting and masking bits, from Bits, bytes and number representation. Reusing an earlier answer is also the core idea of dynamic programming, later in the track.

Not started

Sign in to save your learning progress.

Sign in to save