diff --git a/3sum/sun912.py b/3sum/sun912.py new file mode 100644 index 000000000..275f88cef --- /dev/null +++ b/3sum/sun912.py @@ -0,0 +1,25 @@ +""" + TC: O(n^2) + SC: O(1) +""" + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + result = set() + nums.sort() + + for i in range(len(nums)-2): + left,right = i+1, len(nums)-1 + while left < right: + three_sum = nums[i]+nums[left]+nums[right] + + if three_sum < 0: + left += 1 + elif three_sum > 0: + right -= 1 + else: + result.add((nums[i], nums[left], nums[right])) + left,right = left+1, right-1 + + return list(result) + diff --git a/best-time-to-buy-and-sell-stock/sun912.py b/best-time-to-buy-and-sell-stock/sun912.py new file mode 100644 index 000000000..8bb626639 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sun912.py @@ -0,0 +1,21 @@ +""" +TC: O(n) +SC: O(1) +""" +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit= 0 + l = 0 + r = 1 + + while r < len(prices): + if prices[l] < prices[r]: + profit = prices[r] - prices[l] + max_profit = max(max_profit, profit) + + else: + l = r + r +=1 + return max_profit + + diff --git a/group-anagrams/sun912.py b/group-anagrams/sun912.py new file mode 100644 index 000000000..2472021dd --- /dev/null +++ b/group-anagrams/sun912.py @@ -0,0 +1,19 @@ +""" + TC: O(m*n) + SC: O(26*n) -> O(n) +""" + +from collections import defaultdict + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + result = defaultdict(list) + + for word in strs: + count = [0] * 26 + + for c in word: + count[ord(c)-ord("a")] += 1 + result[tuple(count)].append(word) + + return result.values()