Workspace Counting Bits
0d
DSA Problem Sheet

Counting Bits

Return the count of set bits for every integer from zero through target. The input values list is unused.

EXECUTION LAB

Return the count of set bits for every integer from zero through target. The input values list is unused.

Input and constraints
  • Target must be between 0 and 100.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
dp = [0] * ((target + 1))
i = 1
while (i <= target):
dp[i] = (dp[(i // 2)] + (i & 1))
i = (i + 1)
return dp

Visualizer

Step 1 of 6
00
10i
20
30
40
50

Reuse the shorter prefix and add its final bit

Reuse the shorter prefix and add its final bit.

Variable watch

i 1

Step explanation

Reuse the shorter prefix and add its final bit.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(t) time · O(t) output space

Worked explanation

Reuse the tally for a shorter string of switches, then inspect just the new switch.

Guided solution

Removing the last binary digit halves the number. Add the discarded low bit to the known count for that smaller number.

O(t) time · O(t) output auxiliary space

Examples

Worked example · {"values":[],"target":5} ⇒ [0,1,1,2,1,2]

Edge case 1 · {"values":[],"target":0} ⇒ [0]

Edge case 2 · {"values":[],"target":1} ⇒ [0,1]

Progressive hints

Hint 1Reuse the tally for a shorter string of switches, then inspect just the new switch.
Hint 2Removing the last binary digit halves the number. Add the discarded low bit to the known count for that smaller number.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Using the count of i minus one without accounting for carries fails at powers of two.

Interview follow-up

How would you process a very large target in blocks?