diff --git a/best-time-to-buy-and-sell-stock/jylee2033.py b/best-time-to-buy-and-sell-stock/jylee2033.py new file mode 100644 index 000000000..8e4c7e416 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/jylee2033.py @@ -0,0 +1,27 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # When length is 1, no profit possible + if len(prices) == 1: + return 0 + + buy = 10 ** 5 + profit = 0 + + # Iterate through prices + for price in prices: + # if price < buy: + # buy = price + + # for j in range(i + 1, len(prices)): + # if prices[j] <= buy: + # continue + + # if prices[j] - buy > profit: + # profit = prices[j] - buy + buy = min(buy, price) + profit = max(profit, price - buy) + + return profit + +# Time Complexity: O(n) +# Space Complexity: O(1) diff --git a/encode-and-decode-strings/jylee2033.py b/encode-and-decode-strings/jylee2033.py new file mode 100644 index 000000000..c11d44443 --- /dev/null +++ b/encode-and-decode-strings/jylee2033.py @@ -0,0 +1,58 @@ +class Solution: + """ + @param: strs: a list of strings + @return: encodes a list of strings to a single string. + """ + def encode(self, strs): + # write your code here + # Encode each word with its length prefix and a "#" + # ["C#", "&"] -> "2#C#1#&" + encoded_str = "" + + for word in strs: + encoded_str += f"{len(word)}#{word}" + + return encoded_str + + """ + @param: str: A string + @return: decodes a single string to a list of strings + """ + def decode(self, str): + # write your code here + # "2#C#1#&" -> ["C#", "&"] + decoded_lst = [] + char_count = 0 + reading_word = False + word = "" + length_str = "" + + if str == "": + return [""] + + for ch in str: + if ch == "#" and not reading_word: + # Finished reading the length prefix + # Switch to word-reading mode + char_count = int(length_str) + length_str = "" + reading_word = True + + elif not reading_word: + # Accumulate digits for the length prefix + length_str += ch + + else: + # reading_word is True + word += ch + char_count -= 1 + + if char_count == 0: + reading_word = False + decoded_lst.append(word) + word = "" + + return decoded_lst + +# Time Complexity: O(N) +# Space Complexity: O(N) diff --git a/group-anagrams/jylee2033.py b/group-anagrams/jylee2033.py new file mode 100644 index 000000000..120e9cc5b --- /dev/null +++ b/group-anagrams/jylee2033.py @@ -0,0 +1,14 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagram_map = {} + for word in strs: + key = "".join(sorted(word)) + if key not in anagram_map: + anagram_map[key] = [word] + else: + anagram_map[key].append(word) + + return list(anagram_map.values()) + +# Time Complexity: O(N * K log K), N - number of strings, K - maximum length of a string (for sorting) +# Space Complexity: O(N * K)