Skip to content

Commit 3d5afa0

Browse files
committed
Solved LeetCode 338 using dynamic programming by deriving each bit count from its half and least significant bit with runtime = 2ms.
1 parent 76faed3 commit 3d5afa0

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package LeetCode.DynamicProgramming;
2+
3+
public class LeetCode_338_CountingBits {
4+
public static void main(String[] args) {
5+
6+
int n = 5;
7+
8+
int[] answer = countBits(n);
9+
10+
for (int bit : answer) {
11+
System.out.print(bit + " ");
12+
}
13+
}
14+
15+
/*
16+
Dynamic Programming Approach :
17+
18+
Let: bits[i] = Number of set bits in i
19+
20+
Observation: Dividing a number by 2 removes its least significant bit.
21+
22+
Therefore, bits[i] = bits[i / 2] + (i % 2)
23+
24+
where: bits[i / 2] gives the number of set bits after removing the last bit and (i % 2) tells whether the removed bit was 0 or 1.
25+
*/
26+
static int[] countBits(int n) {
27+
28+
// bits[i] stores the number of set bits in i.
29+
int[] bits = new int[n + 1];
30+
31+
// bits[0] is already 0.
32+
33+
// Compute the answer for every number from 1 to n.
34+
for (int i = 1; i <= n; i++) {
35+
36+
// Remove the last bit by dividing by 2. Add 1 if the removed bit was 1, otherwise add 0.
37+
bits[i] = bits[i / 2] + (i % 2);
38+
}
39+
40+
return bits;
41+
}
42+
}
43+
44+
/*
45+
---------------------------------------------------------
46+
Complexity Analysis
47+
---------------------------------------------------------
48+
49+
Let: n = input number
50+
51+
---------------------------------------------------------
52+
53+
Time Complexity: O(n)
54+
55+
Reason: Each number from 1 to n is processed exactly once.
56+
57+
Overall: O(n)
58+
59+
---------------------------------------------------------
60+
61+
Space Complexity: O(n)
62+
63+
Reason: An array of size (n + 1) is used to store the number of set bits for every integer.
64+
65+
Overall: O(n)
66+
67+
---------------------------------------------------------
68+
69+
Key Observation:
70+
71+
The number of set bits in a number can be derived from the result of half of that number.
72+
73+
Since: bits[i] = bits[i / 2] + (i % 2) every answer is built using a previously computed value, making Dynamic Programming possible.
74+
75+
---------------------------------------------------------
76+
*/

0 commit comments

Comments
 (0)