Skip to content

Commit 6fafc33

Browse files
authored
Merge pull request #450 from sun912/main
[sun] WEEK 5 solution
2 parents 2ff5051 + 7e17910 commit 6fafc33

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

3sum/sun912.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
TC: O(n^2)
3+
SC: O(1)
4+
"""
5+
6+
class Solution:
7+
def threeSum(self, nums: List[int]) -> List[List[int]]:
8+
result = set()
9+
nums.sort()
10+
11+
for i in range(len(nums)-2):
12+
left,right = i+1, len(nums)-1
13+
while left < right:
14+
three_sum = nums[i]+nums[left]+nums[right]
15+
16+
if three_sum < 0:
17+
left += 1
18+
elif three_sum > 0:
19+
right -= 1
20+
else:
21+
result.add((nums[i], nums[left], nums[right]))
22+
left,right = left+1, right-1
23+
24+
return list(result)
25+
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
TC: O(n)
3+
SC: O(1)
4+
"""
5+
class Solution:
6+
def maxProfit(self, prices: List[int]) -> int:
7+
max_profit= 0
8+
l = 0
9+
r = 1
10+
11+
while r < len(prices):
12+
if prices[l] < prices[r]:
13+
profit = prices[r] - prices[l]
14+
max_profit = max(max_profit, profit)
15+
16+
else:
17+
l = r
18+
r +=1
19+
return max_profit
20+
21+

group-anagrams/sun912.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
TC: O(m*n)
3+
SC: O(26*n) -> O(n)
4+
"""
5+
6+
from collections import defaultdict
7+
8+
class Solution:
9+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
10+
result = defaultdict(list)
11+
12+
for word in strs:
13+
count = [0] * 26
14+
15+
for c in word:
16+
count[ord(c)-ord("a")] += 1
17+
result[tuple(count)].append(word)
18+
19+
return result.values()

0 commit comments

Comments
 (0)