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 - Dynamic Programming INPUT Given: n = 2 Numbers to process: 0, 1, 2 Binary Representations 0 00 0 ones 1 01 1 one 2 10 1 one Input: n = 2 ALGORITHM STEPS 1 Initialize DP Array dp[0] = 0 (base case) 2 DP Recurrence dp[i] = dp[i/2] + (i%2) 3 Compute for i=1 dp[1] = dp[0] + 1 = 1 4 Compute for i=2 dp[2] = dp[1] + 0 = 1 DP Table Build i binary dp[i] formula 0 00 0 base 1 01 1 0+1 2 10 1 1+0 FINAL RESULT Bit Count Array 0 ans[0] 1 ans[1] 1 ans[2] 0 has 0 ones in binary 1 has 1 one in binary 2 has 1 one in binary Output: [0, 1, 1] OK Key Insight: The number of 1-bits in i equals dp[i/2] + (i mod 2). Right-shifting i by 1 gives i/2, and the last bit (i mod 2) tells us if we need to add 1. This gives O(n) time complexity. TutorialsPoint - Counting Bits | Dynamic Programming Approach
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