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.
Table of Content
[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
0tonand count the set bits in each number individually by checking every bit position. Store the count obtained for each number in the result array.
#include <iostream>
#include <vector>
using namespace std;
// Function to count set bits for all numbers from 0 to n
vector<int> countBits(int n)
{
// Stores count of set bits for each number
vector<int> ans;
// Process every number from 0 to n
for (int i = 0; i <= n; i++)
{
int cnt = 0;
int num = i;
// Count set bits in current number
while (num > 0)
{
cnt += (num & 1);
num >>= 1;
}
ans.push_back(cnt);
}
return ans;
}
// Driver Code
int main()
{
int n = 7;
vector<int> res = countBits(n);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i != res.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
import java.util.ArrayList;
import java.util.List;
// Function to count set bits for all numbers from 0 to n
public class GfG {
public static List<Integer> countBits(int n)
{
// Stores count of set bits for each number
List<Integer> ans = new ArrayList<>();
// Process every number from 0 to n
for (int i = 0; i <= n; i++) {
int cnt = 0;
int num = i;
// Count set bits in current number
while (num > 0) {
cnt += (num & 1);
num >>= 1;
}
ans.add(cnt);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int n = 7;
List<Integer> res = countBits(n);
System.out.print("[");
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i));
if (i != res.size() - 1)
System.out.print(", ");
}
System.out.print("]");
}
}
def countBits(n):
# Stores count of set bits for each number
ans = []
# Process every number from 0 to n
for i in range(n + 1):
cnt = 0
num = i
# Count set bits in current number
while num > 0:
cnt += (num & 1)
num >>= 1
ans.append(cnt)
return ans
# Driver Code
if __name__ == "__main__":
n = 7
res = countBits(n)
print("[", end="")
for i in range(len(res)):
print(res[i], end="")
if i != len(res) - 1:
print(", ", end="")
print("]")
using System;
using System.Collections.Generic;
// Function to count set bits for all numbers from 0 to n
public class GfG {
public static List<int> countBits(int n)
{
// Stores count of set bits for each number
List<int> ans = new List<int>();
// Process every number from 0 to n
for (int i = 0; i <= n; i++) {
int cnt = 0;
int num = i;
// Count set bits in current number
while (num > 0) {
cnt += (num & 1);
num >>= 1;
}
ans.Add(cnt);
}
return ans;
}
// Driver Code
public static void Main()
{
int n = 7;
List<int> res = countBits(n);
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i != res.Count - 1)
Console.Write(", ");
}
Console.Write("]");
}
}
// Function to count set bits for all numbers from 0 to n
function countBits(n) {
// Stores count of set bits for each number
let ans = [];
// Process every number from 0 to n
for (let i = 0; i <= n; i++) {
let cnt = 0;
let num = i;
// Count set bits in current number
while (num > 0) {
cnt += (num & 1);
num >>= 1;
}
ans.push(cnt);
}
return ans;
}
// Driver Code
let n = 7;
let res = countBits(n);
console.log(`[${res.join(', ')}]`);
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 ini >> 1plus1if the least significant bit ofiis set. Using this relation, we can build the answer for all numbers from0tonin 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].
#include <iostream>
#include <vector>
using namespace std;
vector<int> countBits(int n)
{
// Stores the count of set bits for each number from 0 to n
vector<int> bits(n + 1, 0);
// Compute set bit count using dynamic programming
for (int i = 1; i <= n; i++)
{
// Count of set bits in i equals the count of set bits
// in i >> 1 plus 1 if the least significant bit is set
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
// Driver Code
int main()
{
int n = 7;
vector<int> res = countBits(n);
cout << "[";
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
if (i != res.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
import java.util.Arrays;
public class GfG {
public static int[] countBits(int n)
{
// Stores the count of set bits for each number from
// 0 to n
int[] bits = new int[n + 1];
// Compute set bit count using dynamic programming
for (int i = 1; i <= n; i++) {
// Count of set bits in i equals the count of
// set bits in i >> 1 plus 1 if the least
// significant bit is set
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
// Driver Code
public static void main(String[] args)
{
int n = 7;
int[] res = countBits(n);
System.out.println(Arrays.toString(res));
}
}
def countBits(n):
# Stores the count of set bits for each number from 0 to n
bits = [0] * (n + 1)
# Compute set bit count using dynamic programming
for i in range(1, n + 1):
# Count of set bits in i equals the count of set bits
# in i >> 1 plus 1 if the least significant bit is set
bits[i] = bits[i >> 1] + (i & 1)
return bits
# Driver Code
if __name__ == "__main__":
n = 7
res = countBits(n)
print("[", end="")
for i in range(len(res)):
print(res[i], end="")
if i != len(res) - 1:
print(", ", end="")
print("]")
using System;
using System.Collections.Generic;
public class GfG {
public static List<int> countBits(int n)
{
// Stores the count of set bits for each number from
// 0 to n
List<int> bits = new List<int>(new int[n + 1]);
// Compute set bit count using dynamic programming
for (int i = 1; i <= n; i++) {
// Count of set bits in i equals the count of
// set bits in i >> 1 plus 1 if the least
// significant bit is set
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
// Driver Code
public static void Main()
{
int n = 7;
List<int> res = countBits(n);
Console.WriteLine("[" + string.Join(", ", res)
+ "]");
}
}
function countBits(n) {
// Stores the count of set bits for each number from 0 to n
let bits = new Array(n + 1).fill(0);
// Compute set bit count using dynamic programming
for (let i = 1; i <= n; i++) {
// Count of set bits in i equals the count of set bits
// in i >> 1 plus 1 if the least significant bit is set
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
// Driver Code
let n = 7;
let res = countBits(n);
console.log(`[${res.join(', ')}]`);
Output
[0, 1, 1, 2, 1, 2, 2, 3]