Counting Bits - Problem

Given an integer n, return an array ans of length n + 1 such that for each i (where 0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

For example, if n = 2, the array should contain the count of 1-bits for numbers 0, 1, and 2:

  • 0 in binary is 0 → 0 ones
  • 1 in binary is 1 → 1 one
  • 2 in binary is 10 → 1 one

So the result would be [0, 1, 1].

Input & Output

Example 1 — Basic Case
$ Input: n = 2
Output: [0,1,1]
💡 Note: 0 in binary: 0 → 0 ones, 1 in binary: 1 → 1 one, 2 in binary: 10 → 1 one. Result: [0,1,1]
Example 2 — Larger Range
$ Input: n = 5
Output: [0,1,1,2,1,2]
💡 Note: Count 1-bits: 0→0, 1→1, 2(10)→1, 3(11)→2, 4(100)→1, 5(101)→2
Example 3 — Single Number
$ Input: n = 0
Output: [0]
💡 Note: Only need to count bits for 0, which has zero 1-bits

Constraints

  • 0 ≤ n ≤ 105

Visualization

Tap to expand
Counting Bits: From Numbers to 1-bit CountsInput: n = 50123450₂1₂10₂11₂100₂101₂Count 1-bits in each binary representation011212Output: [0,1,1,2,1,2]Each position contains the count of 1-bits for that index
Understanding the Visualization
1
Input
Given n, we need counts for 0, 1, 2, ..., n
2
Process
Count 1-bits in binary representation of each number
3
Output
Array where ans[i] = count of 1-bits in i
Key Takeaway
🎯 Key Insight: Use dynamic programming to build each result from previously computed smaller numbers
Asked in
Apple 25 Microsoft 20 Google 15
523.0K Views
High Frequency
~15 min Avg. Time
8.4K 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