VOOZH about

URL: https://www.geeksforgeeks.org/dsa/build-bit-count-array/

⇱ Build Bit Count Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Build Bit Count Array

Last Updated : 13 Jun, 2026

Given an integer n, return an array containing the number of set bits (1s) in the binary representation of every integer in the range [0, n].

Examples :

Input: n = 3
Output: [0, 1, 1, 2]
Explanation: The numbers from 0 to 3 have 0, 1, 1, and 2 set bits respectively.

Input: n = 7
Output: [0, 1, 1, 2, 1, 2, 2, 3]
Explanation: The numbers from 0 to 7 have 0, 1, 1, 2, 1, 2, 2, and 3 set bits respectively.

[Naive Approach] Count Set Bits for Each Number - O(n log n) Time and O(1) Space

The idea is to iterate through all numbers from 0 to n and count the set bits in each number individually by checking every bit position. Store the count obtained for each number in the result array.


Output
[0, 1, 1, 2, 1, 2, 2, 3]

[Expected Approach] Using Dynamic Programming - O(n) Time and O(n) Space

The idea is to use the count of set bits of a smaller number to compute the count for a larger number. For any number i, the count of set bits equals the count of set bits in i >> 1 plus 1 if the least significant bit of i is set. Using this relation, we can build the answer for all numbers from 0 to n in a bottom-up manner.

Let us understand with example:
Input: n = 7

  • Initialize bits = [0, 0, 0, 0, 0, 0, 0, 0], where bits[i] stores the count of set bits in i.
  • For i = 1, bits[1] = bits[0] + (1 & 1) = 0 + 1 = 1. Now, bits = [0, 1, 0, 0, 0, 0, 0, 0].
  • For i = 2 and i = 3, bits[2] = bits[1] + 0 = 1 and bits[3] = bits[1] + 1 = 2. Now, bits = [0, 1, 1, 2, 0, 0, 0, 0].
  • For i = 4, i = 5, and i = 6, we get bits[4] = 1, bits[5] = 2, and bits[6] = 2. Now, bits = [0, 1, 1, 2, 1, 2, 2, 0].
  • For i = 7, bits[7] = bits[3] + 1 = 2 + 1 = 3. The final array becomes [0, 1, 1, 2, 1, 2, 2, 3].

Output
[0, 1, 1, 2, 1, 2, 2, 3]
Comment
Article Tags:
Article Tags: