diff --git a/3sum/Leo.py b/3sum/Leo.py new file mode 100644 index 000000000..6b952a5ef --- /dev/null +++ b/3sum/Leo.py @@ -0,0 +1,26 @@ +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + + nums.sort() + res = [] + + for i, ch in enumerate(nums): + if i > 0 and nums[i] == nums[i - 1]: continue + + l, r = i + 1, len(nums) - 1 + while l < r: + threeSum = ch + nums[l] + nums[r] + + if threeSum < 0: + l += 1 + elif threeSum > 0: + r -= 1 + else: + res.append([ch, nums[l], nums[r]]) + l += 1 + while l < r and nums[l] == nums[l - 1]: + l += 1 + + return res + + ## TC: O(n^2), SC: O(1) diff --git a/encode-and-decode-strings/Leo.py b/encode-and-decode-strings/Leo.py new file mode 100644 index 000000000..61f295a35 --- /dev/null +++ b/encode-and-decode-strings/Leo.py @@ -0,0 +1,26 @@ +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string. + """ + res = '' + + for s in strs: + res += str(len(s)) + '#' + s + + return res + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings. + """ + res = [] + + i = 0 + while i < len(s): + a = s.find('#', i) + length = int(s[i:a]) + res.append(s[a + 1:a + 1 + length]) + i = a + 1 + length + + return res + + ## TC: O(n), SC:O(n),n denotes sum of all len(s) diff --git a/longest-consecutive-sequence/Leo.py b/longest-consecutive-sequence/Leo.py new file mode 100644 index 000000000..b5c43afff --- /dev/null +++ b/longest-consecutive-sequence/Leo.py @@ -0,0 +1,18 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + + seen = set(nums) + longest = 0 + + for n in seen: + if (n - 1) not in seen: + length = 1 + + while (n + length) in seen: + length += 1 + + longest = max(length, longest) + + return longest + + ## TC: O(n), SC: O(n) diff --git a/product-of-array-except-self/Leo.py b/product-of-array-except-self/Leo.py new file mode 100644 index 000000000..5a692524d --- /dev/null +++ b/product-of-array-except-self/Leo.py @@ -0,0 +1,16 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + length = len(nums) + res = [1] * length + ltor = 1 + rtol = 1 + + for i in range(length): + res[i] *= ltor + ltor = ltor * nums[i] + res[length - i - 1] *= rtol + rtol = rtol * nums[length - i - 1] + + return res + + ## TC: O(n), SC: O(1) diff --git a/top-k-frequent-elements/Leo.py b/top-k-frequent-elements/Leo.py new file mode 100644 index 000000000..75c26468a --- /dev/null +++ b/top-k-frequent-elements/Leo.py @@ -0,0 +1,17 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + + num_dict = collections.Counter(nums) + freq = num_dict.most_common() + ans = [] + + for key, val in freq: + if k == 0: + break + + ans.append(key) + k -= 1 + + return ans + + ## TC: O(n * logn), SC: O(n)