Skip to content

[Leo] 4th Week solutions #91

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions counting-bits/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution:
def countBits(self, n: int) -> List[int]:
counter = [0]

for i in range(1, n + 1):
counter.append(counter[i >> 1] + i % 2)

return counter

## TC: O(n), SC: O(n)
## this question should be under math section tbh
22 changes: 22 additions & 0 deletions group-anagrams/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = collections.defaultdict(list)

for s in strs:
ans[str(sorted(s))].append(s)

return list(ans.values())

## TC: O(n * klogk), SC: O(n * k), where n is len(strs) and k is len(longest_s)

# ans = {}

# for s in strs:
# sorted_s = ''.join(sorted(s))

# if sorted_s not in ans:
# ans[sorted_s] = []

# ans[sorted_s].append(s)

# return list(ans.values())
8 changes: 8 additions & 0 deletions missing-number/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)

return int(n * (n + 1) / 2 - sum(nums))

# TC: O(n), SC: O(1)
# this only works for "only missing number", if there are multiple missing numbers, this won't work
19 changes: 19 additions & 0 deletions number-of-1-bits/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution:
def hammingWeight(self, n: int) -> int:
counter = 0

while n:
counter += 1
n = n & (n - 1)

return counter

## TC: O(k), SC: O(1), since given int(n) has constant length

# counter = 0

# for i in bin(n):
# if i == "1":
# counter += 1

# return counter
16 changes: 16 additions & 0 deletions reverse-bits/Leo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def reverseBits(self, n: int) -> int:

res = 0

for i in range(32):
if n & 1:
res += 1 << (31 - i)
n >>= 1

return res

# TC: O(1), SC: O(1) for both codes

# n = bin(n)[2:].zfill(32)
# return int(n[::-1], 2)