Counting Bits - Problem
Counting Bits in Binary Representations

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
Binary Pattern Recognition: Smart Bit CountingNumberBinaryRight ShiftPatternCount611011 (3)Same as 3 + 02711111 (3)Same as 3 + 1381000100 (4)Same as 4 + 0191001100 (4)Same as 4 + 12Magic Formula: dp[i] = dp[i >> 1] + (i & 1)Right shift removes last bit, then add it back if it was 1!⚡ O(n) time by reusing previous calculations instead of counting from scratch!
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 25
47.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen