diff --git a/counting-bits/samthekorean.py b/counting-bits/samthekorean.py new file mode 100644 index 0000000000..1ecf564cec --- /dev/null +++ b/counting-bits/samthekorean.py @@ -0,0 +1,10 @@ +# TC: O(n) +# SC: O(n) +# For each number from 1 to n, update the count of set bits for i based on the count for i divided by two +# and the least significant bit (LSB) of i. +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0] * (n + 1) + for i in range(1, n + 1): + ans[i] = ans[i >> 1] + (i & 1) + return ans diff --git a/group-anagrams/samthekorean.py b/group-anagrams/samthekorean.py new file mode 100644 index 0000000000..4ea2fcf085 --- /dev/null +++ b/group-anagrams/samthekorean.py @@ -0,0 +1,15 @@ +# TC : O(nwlog(w)) +# 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) +# SC : O(w*n) +from collections import defaultdict + + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagrams = defaultdict(list) + + # 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 + for word in strs: + anagrams[str(sorted(word))].append(word) + + return anagrams.values() diff --git a/missing-number/samthekorean.py b/missing-number/samthekorean.py new file mode 100644 index 0000000000..76f73dce50 --- /dev/null +++ b/missing-number/samthekorean.py @@ -0,0 +1,14 @@ +# TC : O(n) +# SC : O(1) +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + + # The sum of the numbers in the range(0,n) + sumOfNums = (1 + n) * n // 2 + + # Subtract every element of nums to leave only missing number + for num in nums: + sumOfNums -= num + + return sumOfNums diff --git a/number-of-1-bits/samthekorean.py b/number-of-1-bits/samthekorean.py new file mode 100644 index 0000000000..192476c843 --- /dev/null +++ b/number-of-1-bits/samthekorean.py @@ -0,0 +1,11 @@ +# TC : O(log n) +# reason : bin method internally devides n by 2 while transitioning to binary number +# SC : O(1) +class Solution: + def hammingWeight(self, n: int) -> int: + res = 0 + # count each charactor from the first + for bit in bin(n): + if bit == "1": + res += 1 + return res diff --git a/reverse-bits/samthekorean.py b/reverse-bits/samthekorean.py new file mode 100644 index 0000000000..d6fe44eaca --- /dev/null +++ b/reverse-bits/samthekorean.py @@ -0,0 +1,9 @@ +# TC : O(1) +# SC : O(1) +# Reason : The input is fixed to be 32 bit resulting in time and space complexity being O(1) +class Solution: + def reverseBits(self, n: int) -> int: + binary_string = bin(n)[2:].zfill(32) + reversed_binary_string = binary_string[::-1] + + return int(reversed_binary_string, 2)