Counting Bits
Return the count of set bits for every integer from zero through target. The input values list is unused.
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 dpVisualizer
Step 1 of 6Reuse the shorter prefix and add its final bit
Reuse the shorter prefix and add its final bit.
Variable watch
Step explanation
Reuse the shorter prefix and add its final bit.
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 1
Reuse the tally for a shorter string of switches, then inspect just the new switch.Hint 2
Removing the last binary digit halves the number. Add the discarded low bit to the known count for that smaller number.Hint 3
Step 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?