Skip to content

Commit 94adc07

Browse files
committed
solve counting bit with O(n) complexity
1 parent c528fd2 commit 94adc07

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

counting-bits/samthekorean.py

+7-12
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
1-
# TC : O(nlog(n))
2-
# SC : O(n)
1+
# TC: O(n)
2+
# SC: O(n)
3+
# For each number from 1 to n, update the count of set bits for i based on the count for i divided by two
4+
# and the least significant bit (LSB) of i.
35
class Solution:
46
def countBits(self, n: int) -> List[int]:
5-
count = 0
6-
ans = []
7-
8-
for i in range(n + 1):
9-
while i > 0:
10-
count += i % 2
11-
i = i // 2
12-
ans.append(count)
13-
count = 0
14-
7+
ans = [0] * (n + 1)
8+
for i in range(1, n + 1):
9+
ans[i] = ans[i >> 1] + (i & 1)
1510
return ans

0 commit comments

Comments
 (0)