Counting Bits - Problem
Counting Bits in Binary Representations
Given an integer
Your task: Return an array
Example: For
• 0 →
• 1 →
• 2 →
• 3 →
• 4 →
• 5 →
So the result would be
Given an integer
n, you need to create an array that contains the count of 1-bits in the binary representation of every number from 0 to n inclusive.Your task: Return an array
ans of length n + 1 where ans[i] represents the number of 1's in the binary representation of number i.Example: For
n = 5, the binary representations are:• 0 →
0 (zero 1's)• 1 →
1 (one 1)• 2 →
10 (one 1)• 3 →
11 (two 1's)• 4 →
100 (one 1)• 5 →
101 (two 1's)So the result would be
[0, 1, 1, 2, 1, 2]. Input & Output
example_1.py — Basic Case
$
Input:
n = 2
›
Output:
[0, 1, 1]
💡 Note:
0 → 0 (0 ones), 1 → 1 (1 one), 2 → 10 (1 one)
example_2.py — Medium Case
$
Input:
n = 5
›
Output:
[0, 1, 1, 2, 1, 2]
💡 Note:
0→0(0), 1→1(1), 2→10(1), 3→11(2), 4→100(1), 5→101(2)
example_3.py — Edge Case
$
Input:
n = 0
›
Output:
[0]
💡 Note:
Only number 0, which has 0 ones in its binary representation
Constraints
- 0 ≤ n ≤ 105
- Follow up: Can you solve it in O(n) time?
- Challenge: Can you do it without using built-in functions?
Visualization
Tap to expand
Understanding the Visualization
1
Notice the Pattern
Each number's bit count relates to a smaller number
2
Right Shift Insight
i >> 1 gives us the number with the rightmost bit removed
3
Add Last Bit
i & 1 tells us if the last bit was 1 or 0
4
Build Solution
Combine these insights: dp[i] = dp[i >> 1] + (i & 1)
Key Takeaway
🎯 Key Insight: Every number's bit pattern reuses most bits from a smaller number (i >> 1), we just need to account for the rightmost bit!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code