Skip to content

Commit 7a067f7

Browse files
authored
Merge pull request #2503 from jylee2033/main
[jylee2033] WEEK 05 solutions
2 parents 7acbc80 + 00dd7c7 commit 7a067f7

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
# When length is 1, no profit possible
4+
if len(prices) == 1:
5+
return 0
6+
7+
buy = 10 ** 5
8+
profit = 0
9+
10+
# Iterate through prices
11+
for price in prices:
12+
# if price < buy:
13+
# buy = price
14+
15+
# for j in range(i + 1, len(prices)):
16+
# if prices[j] <= buy:
17+
# continue
18+
19+
# if prices[j] - buy > profit:
20+
# profit = prices[j] - buy
21+
buy = min(buy, price)
22+
profit = max(profit, price - buy)
23+
24+
return profit
25+
26+
# Time Complexity: O(n)
27+
# Space Complexity: O(1)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution:
2+
"""
3+
@param: strs: a list of strings
4+
@return: encodes a list of strings to a single string.
5+
"""
6+
def encode(self, strs):
7+
# write your code here
8+
# Encode each word with its length prefix and a "#"
9+
# ["C#", "&"] -> "2#C#1#&"
10+
encoded_str = ""
11+
12+
for word in strs:
13+
encoded_str += f"{len(word)}#{word}"
14+
15+
return encoded_str
16+
17+
"""
18+
@param: str: A string
19+
@return: decodes a single string to a list of strings
20+
"""
21+
def decode(self, str):
22+
# write your code here
23+
# "2#C#1#&" -> ["C#", "&"]
24+
decoded_lst = []
25+
char_count = 0
26+
reading_word = False
27+
word = ""
28+
length_str = ""
29+
30+
if str == "":
31+
return [""]
32+
33+
for ch in str:
34+
if ch == "#" and not reading_word:
35+
# Finished reading the length prefix
36+
# Switch to word-reading mode
37+
char_count = int(length_str)
38+
length_str = ""
39+
reading_word = True
40+
41+
elif not reading_word:
42+
# Accumulate digits for the length prefix
43+
length_str += ch
44+
45+
else:
46+
# reading_word is True
47+
word += ch
48+
char_count -= 1
49+
50+
if char_count == 0:
51+
reading_word = False
52+
decoded_lst.append(word)
53+
word = ""
54+
55+
return decoded_lst
56+
57+
# Time Complexity: O(N)
58+
# Space Complexity: O(N)

group-anagrams/jylee2033.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3+
anagram_map = {}
4+
for word in strs:
5+
key = "".join(sorted(word))
6+
if key not in anagram_map:
7+
anagram_map[key] = [word]
8+
else:
9+
anagram_map[key].append(word)
10+
11+
return list(anagram_map.values())
12+
13+
# Time Complexity: O(N * K log K), N - number of strings, K - maximum length of a string (for sorting)
14+
# Space Complexity: O(N * K)

0 commit comments

Comments
 (0)