diff --git a/counting-bits/Leo.py b/counting-bits/Leo.py new file mode 100644 index 000000000..ec1142d5d --- /dev/null +++ b/counting-bits/Leo.py @@ -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 diff --git a/group-anagrams/Leo.py b/group-anagrams/Leo.py new file mode 100644 index 000000000..3aa4f9822 --- /dev/null +++ b/group-anagrams/Leo.py @@ -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()) diff --git a/missing-number/Leo.py b/missing-number/Leo.py new file mode 100644 index 000000000..1e6d30127 --- /dev/null +++ b/missing-number/Leo.py @@ -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 diff --git a/number-of-1-bits/Leo.py b/number-of-1-bits/Leo.py new file mode 100644 index 000000000..2675c6b02 --- /dev/null +++ b/number-of-1-bits/Leo.py @@ -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 diff --git a/reverse-bits/Leo.py b/reverse-bits/Leo.py new file mode 100644 index 000000000..3fca085cc --- /dev/null +++ b/reverse-bits/Leo.py @@ -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)