Solution: Counting Bits
Let's solve the Counting Bits problem using the Dynamic Programming pattern.
Statement
For a given positive integer, n
, your task is to return an array of length such that for each where , result[x]
is the count of s in the binary representation of .
Constraints:
Solution
So far, you have probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.
Naive approach
The naive approach for this solution would be to iterate through the string character by character. During the traversal, we convert each number to its binary representation, count the number of
This approach would have a time complexity of
Optimized approach using dynamic programming
The problem involves using a dynamic programming approach to calculate and store the count of
For every digit, we know it can be an even number or an odd number. Let’s see how we can compute each by using binary manipulation:
For even numbers, the count can be calculated using the count for half of that number. For example, the count of
bit for equals the count of bit for . We can confirm this by looking at the binary representation of and , which are and , respectively. The count of bit is two in both numbers. For odd numbers, the count is one more than the count for half of that number. For example, the count of
bit for equals the count of bit for extra bit. We can confirm this by looking at the binary representation of and , which are and , respectively. The final count of bit after adding an extra bit to the half number is three.
Now, let’s look at the basic algorithm to solve this problem:
Add base cases where the
and iteration results will be and . Create a 1D table of length
containing all zeros. This will be used to store and recalculate the count of the bits in future iterations. Next, we’ll iterate through the range of numbers from
to . If the number is even for each number in the range, compute result[x] = result[x / 2]
. If the number is odd, computeresult[x] = result[x / 2] + 1
.Finally, return the list containing the number of set bits in the binary representation of the numbers from
to .
The following illustration shows these steps in detail:
Let’s look at the code for this solution below:
public class CountBits {public static int[] countingBits(int n) {int[] result = new int[n + 1];if (n == 0) {return result;}result[0] = 0;result[1] = 1;for (int x = 2; x <= n; ++x) {if ((x % 2) == 0) {result[x] = result[x / 2];}else {result[x] = result[x / 2] + 1;}}return result;}// Driver codepublic static void main(String[] args) {int[] inputBits = { 1, 2, 3, 4, 5, 10 };for (int i = 0; i < inputBits.length; ++i) {System.out.println((i + 1) + ".\t Bits: " + inputBits[i]);int[] result = countingBits(inputBits[i]);System.out.println("\t Counting bits: " + java.util.Arrays.toString(result));System.out.println(new String(new char[100]).replace("\0", "-"));}}}
Solution summary
The solution above can be summarized in the following points:
A DP array is created to store the result of any subproblems encountered during iteration.
During the iteration, we performed two checks for even and odd numbers:
If the current number is even, then search and replace the current index’s value of the DP array with the value stored at half of this number. This is because both digits will have the same number of
bits. Otherwise, add an additional
bit in the case of odd numbers.
Return the last index of the DP array containing the number of set bits in the binary representation of the numbers from
to .
Time complexity
The time complexity of this solution is
Space complexity
The space complexity of this solution is
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.