diff --git a/best-time-to-buy-and-sell-stock/dolphinflow86.py b/best-time-to-buy-and-sell-stock/dolphinflow86.py new file mode 100644 index 0000000000..c2df5e394d --- /dev/null +++ b/best-time-to-buy-and-sell-stock/dolphinflow86.py @@ -0,0 +1,13 @@ +# 1) Keep track of local minimum and use local minimum to update max profile while interating prices. +# TC: O(N) where N is the length of prices +# SC: O(1) +class Solution: + def maxProfit(self, prices: List[int]) -> int: + min_price = prices[0] + max_profit = 0 + + for price in prices: + max_profit = max(max_profit, price - min_price) + min_price = min(min_price, price) + + return max_profit diff --git a/encode-and-decode-strings/dolphinflow86.py b/encode-and-decode-strings/dolphinflow86.py new file mode 100644 index 0000000000..1fadd25f99 --- /dev/null +++ b/encode-and-decode-strings/dolphinflow86.py @@ -0,0 +1,30 @@ +# 1) Prepend each word with its length and a delimiter '%'. +# TC: encode O(N) where N is the len(str), decode O(N) where N is the len(s) +# SC: O(N) for storing the encoded string +class Solution: + + def encode(self, strs: list[str]) -> str: + answer = "" + for s in strs: + answer += f"{len(s)}%{s}" + return answer + + def decode(self, s: str) -> list[str]: + left = 0 + right = 0 + str_len = len(s) + + result = [] + while right < str_len: + while s[right] != "%": + right += 1 + + num_len = int(s[left:right]) + start = right + 1 + word = s[start : start + num_len] + result.append(word) + + left = start + num_len + right = left + + return result diff --git a/group-anagrams/dolphinflow86.py b/group-anagrams/dolphinflow86.py new file mode 100644 index 0000000000..ad9ee569be --- /dev/null +++ b/group-anagrams/dolphinflow86.py @@ -0,0 +1,13 @@ +# 1) Group words by their sorted form using defaultdict. While iterating the strs, sort each word and append original word to the corresponding list. After then convert dict to 2 dimensional list and return the list. +# TC: O(N*LlogL) where N is length of strs, L is max length of a word. +# SC: O(N*L) + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + groups = defaultdict(list) + + for str in strs: + sorted_str = "".join(sorted(str)) + groups[sorted_str].append(str) + + return list(groups.values())