Skip to content

Commit 40b9464

Browse files
authored
Merge pull request #86 from SamTheKorean/solution4
[SAM] Week 4 solutions.
2 parents 36210b0 + 94adc07 commit 40b9464

File tree

5 files changed

+59
-0
lines changed

5 files changed

+59
-0
lines changed

counting-bits/samthekorean.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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.
5+
class Solution:
6+
def countBits(self, n: int) -> List[int]:
7+
ans = [0] * (n + 1)
8+
for i in range(1, n + 1):
9+
ans[i] = ans[i >> 1] + (i & 1)
10+
return ans

group-anagrams/samthekorean.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# TC : O(nwlog(w))
2+
# reason : n being the number of words and w being the length of each word, therefore the total time complexity is n times wlog(w) (time complexity for sorting each word)
3+
# SC : O(w*n)
4+
from collections import defaultdict
5+
6+
7+
class Solution:
8+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
9+
anagrams = defaultdict(list)
10+
11+
# Use sorted word as a string and append it with the original word so the word containing same charactors with the same number of existence can be in the same group
12+
for word in strs:
13+
anagrams[str(sorted(word))].append(word)
14+
15+
return anagrams.values()

missing-number/samthekorean.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# TC : O(n)
2+
# SC : O(1)
3+
class Solution:
4+
def missingNumber(self, nums: List[int]) -> int:
5+
n = len(nums)
6+
7+
# The sum of the numbers in the range(0,n)
8+
sumOfNums = (1 + n) * n // 2
9+
10+
# Subtract every element of nums to leave only missing number
11+
for num in nums:
12+
sumOfNums -= num
13+
14+
return sumOfNums

number-of-1-bits/samthekorean.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# TC : O(log n)
2+
# reason : bin method internally devides n by 2 while transitioning to binary number
3+
# SC : O(1)
4+
class Solution:
5+
def hammingWeight(self, n: int) -> int:
6+
res = 0
7+
# count each charactor from the first
8+
for bit in bin(n):
9+
if bit == "1":
10+
res += 1
11+
return res

reverse-bits/samthekorean.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# TC : O(1)
2+
# SC : O(1)
3+
# Reason : The input is fixed to be 32 bit resulting in time and space complexity being O(1)
4+
class Solution:
5+
def reverseBits(self, n: int) -> int:
6+
binary_string = bin(n)[2:].zfill(32)
7+
reversed_binary_string = binary_string[::-1]
8+
9+
return int(reversed_binary_string, 2)

0 commit comments

Comments
 (0)