Skip to problem
←

Counting Bits

Easy 0 attempts

Given an integer n, build an array of length n+1 where the value at each index i is the count of set bits (1-bits) in the binary representation of i.

Function contract

Implement countBits(n), where n is a non-negative integer.

Output: An array of length n + 1 whose element at index i counts the 1 bits in i’s binary representation, for every i from 0 through n.

Example 1

Input
n = 2
Output
[0,1,1]

Example 2

Input
n = 5
Output
[0,1,1,2,1,2]
Constraints
  • 0 <= n <= 10^5

DP with Bit Trick

ans[i] = ans[i >> 1] + (i & 1).

javascript
function countBits(n) {
  const ans = Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) ans[i] = ans[i >> 1] + (i & 1);
  return ans;
}

Time: O(n + 1) | Space: O(n + 1) for the returned array and O(1) extra space.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript