Skip to content
mlmentorship

Counting Bits

Reuse a smaller integer's completed population count instead of recounting every binary representation.

Published · 17 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Counting Bits

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative integer limit. Output. Return a list of length limit + 1; entry i is the number of ones in i's binary representation. Rules. Include both endpoints, zero and limit, in increasing numeric order. Leading zero bits do not affect the count. The binary representation of zero has no one bits. Negative bounds are outside the contract. Example. For limit = 5, return [0, 1, 1, 2, 1, 2]. Entry 3 is 2 because binary 11 contains two ones. Bound zero returns [0].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

The set-bit count for value reuses the completed count for value >> 1 and adds value & 1.

Problem trace

Reuse the halved number, then add only its discarded low bit

Worked example: reuse the halved number and add its low bitDropping the low bit leaves a smaller number whose count is already known. The unchanged high bits reuse that count. Only the removed low bit can add one more. Work upward from zero instead of recounting every full word.Dropping the low bit reuses thepopcount of the remaining high bitsThirteen: binary 11011101110Six: binary 110; counttwo21Two highbitslow bit3Reuse two high set bits; count thelow one too.
Read it this way: Dropping the low bit leaves a smaller number whose count is already known. The unchanged high bits reuse that count. Only the removed low bit can add one more. Work upward from zero instead of recounting every full word. Which count is reused after dropping the low one bit of binary 1101?
Full interview answer 17 min read

Report the number of binary one bits in every integer from zero through a given bound.

Problem

Input. A nonnegative integer limit.

Output. Return a list of length limit + 1; entry i is the number of ones in i’s binary representation.

Rules. Include both endpoints, zero and limit, in increasing numeric order. Leading zero bits do not affect the count. The binary representation of zero has no one bits. Negative bounds are outside the contract.

Example. For limit = 5, return [0, 1, 1, 2, 1, 2]. Entry 3 is 2 because binary 11 contains two ones. Bound zero returns [0].

Picture

Array index value names an integer, not a bit position. Its stored entry is that integer’s population count.

The arrow points from the value being solved to its completed predecessor, value >> 1.

Problem trace

Separate range example: reuse every smaller ready count

Input and goalReturn the set-bit count for every value from 0 through `n`.
Initialize answer[0]For limit 6, allocate seven cells. Zero has no set bits, so answer[0] = 0 before the loop starts.
v=000?1?2?3?4?5?6
inputlimit = 6invariantentries below the next value are complete
v
0
input
limit = 6
invariant
entries below the next value are complete

Recognize it
The task requests bit counts for every integer in an increasing range, so each answer can reuse a smaller already-computed integer instead of recounting from scratch.
Keep true
Before computing answer[value], all lower indices are correct. Because value >> 1 is smaller, its count is available, and value & 1 contributes exactly the removed low bit.
Reuse it
When a bit operation maps each state to a smaller state, build answers in numeric order and append the removed-bit contribution; similar recurrences use x & (x - 1), highest powers of two, or parity.
For limit 6, allocate seven cells. Zero has no set bits, so answer[0] = 0 before the loop starts. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 6 have the same set-bit count as 3 even though the numeric value is halved?
Reference drawing

Problem trace

Reuse the halved number, then add only its discarded low bit

Worked example: reuse the halved number and add its low bitDropping the low bit leaves a smaller number whose count is already known. The unchanged high bits reuse that count. Only the removed low bit can add one more. Work upward from zero instead of recounting every full word.Dropping the low bit reuses thepopcount of the remaining high bitsThirteen: binary 11011101110Six: binary 110; counttwo21Two highbitslow bit3Reuse two high set bits; count thelow one too.
Execution trace
Input and goalReturn the set-bit count for every value from 0 through `n`.
Initialize answer[0]For limit 6, allocate seven cells. Zero has no set bits, so answer[0] = 0 before the loop starts.
v=000?1?2?3?4?5?6
inputlimit = 6invariantentries below the next value are complete
v
0
input
limit = 6
invariant
entries below the next value are complete

Recognize it
The task requests bit counts for every integer in an increasing range, so each answer can reuse a smaller already-computed integer instead of recounting from scratch.
Keep true
Before computing answer[value], all lower indices are correct. Because value >> 1 is smaller, its count is available, and value & 1 contributes exactly the removed low bit.
Reuse it
When a bit operation maps each state to a smaller state, build answers in numeric order and append the removed-bit contribution; similar recurrences use x & (x - 1), highest powers of two, or parity.
For limit 6, allocate seven cells. Zero has no set bits, so answer[0] = 0 before the loop starts. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 6 have the same set-bit count as 3 even though the numeric value is halved?
Read it this way: Dropping the low bit leaves a smaller number whose count is already known. The unchanged high bits reuse that count. Only the removed low bit can add one more. Work upward from zero instead of recounting every full word. Which count is reused after dropping the low one bit of binary 1101?

Code

For nonnegative integers, right shift removes the low bit. The remaining integer is strictly smaller when value > 0.

value & 1 is exactly the removed contribution: zero or one.

def count_bits(limit: int) -> list[int]:
   answer = [0] * (limit + 1)
   for value in range(1, limit + 1):
      answer[value] = answer[value >> 1] + (value & 1)
   return answer

Why the Read Is Ready

Before each write, every lower-index answer is complete. The smaller predecessor therefore has its final count, not a provisional zero.

The explicit base is answer[0] = 0. Uncomputed cells also contain zero in memory, but the picture marks them ? to distinguish unknown from solved.

For six, read answer[3] = 2 and add its removed zero bit. The result is [0,1,1,2,1,2,2].

Output and Cost

The function performs limit writes and returns limit + 1 integer slots. Under bounded-word arithmetic, time is .

Python’s shifts and bit operations depend on operand width. Returning every answer cannot take only logarithmic output space.

Zero returns [0]. Negative limits are outside the reference contract.

Recall: What certifies a reusable predecessor? It is smaller, already solved, and differs by a known removed contribution.

Remove a Whole Set Bit

Choose this when: The lowest-set-bit identity is the dependency you want to reuse.

Number of 1 Bits proves that value & (value - 1) removes exactly one one.

For positive values, that predecessor is smaller. Add one to its completed count.

def count_bits_by_clear(limit):
   answer = [0] * (limit + 1)
   for value in range(1, limit + 1):
      answer[value] = answer[value & (value - 1)] + 1
   return answer

For six, this reads answer[4] = 1 and adds one. The shift recurrence instead reads answer[3] = 2 and adds zero.

Both return the same table, with the same nonnegative input contract and output-size bound. Their removed contributions differ because their predecessors differ.

Return Only the Total

Choose this when: Only the sum of all counts from zero through limit is required.

Split at the highest power of two, . The complete lower block 0..p-1 contains ones when .

Values p..limit contribute limit - p + 1 leading ones. Their remaining low parts cover 0..limit-p.

def total_set_bits(limit):
   if limit <= 0:
      return 0
   exponent = limit.bit_length() - 1
   power = 1 << exponent
   full_block = exponent * (power >> 1)
   leading_ones = limit - power + 1
   return full_block + leading_ones + total_set_bits(limit - power)

For six, the lower block contributes four, leading ones contribute three, and the remainder contributes two. The total is nine.

Nonpositive input returns zero. At most recursive levels are needed, but dense huge integers can reach Python’s recursion limit.

Each frame holds width-dependent integers; bit costs are not constant. This smaller output contract avoids constructing a linear table.