Skip to main content

Counting Bits

Problem Description​

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

Examples​

Example 1:

Input: n = 2
Output: [0, 1, 1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:

Input: n = 5
Output: [0, 1, 1, 2, 1, 2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Constraints​

  • 0 <= n <= 10^5

Follow-up​

  • Can you solve it in linear time O(n) and possibly in a single pass?
  • Can you solve it without using any built-in function (i.e., like __builtin_popcount in C++)?

Solution for Counting Bits Problem​

Approach 1: Brute Force (Naive)​

The brute force approach involves iterating through each number from 0 to n, converting each number to its binary form, and counting the number of 1s in that binary representation.

Code in Different Languages​

Written by @ImmidiSivani
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1);
for (int i = 0; i <= n; ++i) {
ans[i] = __builtin_popcount(i);
}
return ans;
}
};

Complexity Analysis​

  • Time Complexity: O(nlogn)O(nlogn), as converting a number to binary and counting bits takes O(log⁑n)O(\log n) time, and we do this for each number from 0 to n.
  • Space Complexity: O(n)O(n), for storing the result array.

Approach 2: Optimized Dynamic Programming​

To achieve a linear time solution, we can use a dynamic programming approach. We use the property that the number of 1s in i can be derived from the number of 1s in i >> 1 (i.e., i divided by 2) plus 1 if the last bit of i is 1.

Code in Different Languages​

Written by @ImmidiSivani
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1);
for (int i = 1; i <= n; ++i) {
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
};

Complexity Analysis​

  • Time Complexity: O(n)O(n), as we calculate the number of bits for each number from 0 to n in constant time.
  • Space Complexity: O(n)O(n), for storing the result array.

Authors:

Loading...