Skip to content

Commit f0188c0

Browse files
committed
[Leo] 4th Week solutions
1 parent 36210b0 commit f0188c0

File tree

5 files changed

+76
-0
lines changed

5 files changed

+76
-0
lines changed

counting-bits/Leo.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def countBits(self, n: int) -> List[int]:
3+
counter = [0]
4+
5+
for i in range(1, n + 1):
6+
counter.append(counter[i >> 1] + i % 2)
7+
8+
return counter
9+
10+
## TC: O(n), SC: O(n)
11+
## this question should be under math section tbh

group-anagrams/Leo.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3+
ans = collections.defaultdict(list)
4+
5+
for s in strs:
6+
ans[str(sorted(s))].append(s)
7+
8+
return list(ans.values())
9+
10+
## TC: O(n * klogk), SC: O(n * k), where n is len(strs) and k is len(longest_s)
11+
12+
# ans = {}
13+
14+
# for s in strs:
15+
# sorted_s = ''.join(sorted(s))
16+
17+
# if sorted_s not in ans:
18+
# ans[sorted_s] = []
19+
20+
# ans[sorted_s].append(s)
21+
22+
# return list(ans.values())

missing-number/Leo.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def missingNumber(self, nums: List[int]) -> int:
3+
n = len(nums)
4+
5+
return int(n * (n + 1) / 2 - sum(nums))
6+
7+
# TC: O(n), SC: O(1)
8+
# this only works for "only missing number", if there are multiple missing numbers, this won't work

number-of-1-bits/Leo.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
counter = 0
4+
5+
while n:
6+
counter += 1
7+
n = n & (n - 1)
8+
9+
return counter
10+
11+
## TC: O(n), SC: O(1)
12+
13+
# counter = 0
14+
15+
# for i in bin(n):
16+
# if i == "1":
17+
# counter += 1
18+
19+
# return counter

reverse-bits/Leo.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def reverseBits(self, n: int) -> int:
3+
4+
res = 0
5+
6+
for i in range(32):
7+
if n & 1:
8+
res += 1 << (31 - i)
9+
n >>= 1
10+
11+
return res
12+
13+
# TC: O(1), SC: O(1) for both codes
14+
15+
# n = bin(n)[2:].zfill(32)
16+
# return int(n[::-1], 2)

0 commit comments

Comments
 (0)