Skip to content

Commit bc85846

Browse files
authored
Merge pull request #1531 from ayosecu/main
[ayosecu] Week 9 Solutions
2 parents b5dab63 + e6dba98 commit bc85846

File tree

5 files changed

+223
-0
lines changed

5 files changed

+223
-0
lines changed

linked-list-cycle/ayosecu.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from typing import Optional
2+
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, x):
6+
self.val = x
7+
self.next = None
8+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(n), n = The number of nodes
12+
- Space Complexity: O(1)
13+
"""
14+
def hasCycle(self, head: Optional[ListNode]) -> bool:
15+
if not head:
16+
return False
17+
18+
slow, fast = head, head
19+
while slow and fast:
20+
slow = slow.next
21+
if fast.next:
22+
fast = fast.next.next
23+
else:
24+
return False
25+
26+
if fast == slow:
27+
return True
28+
29+
return False
30+
31+
# Run Test Cases
32+
def do_test():
33+
sol = Solution()
34+
35+
h1 = ListNode(3)
36+
h1.next = ListNode(2)
37+
h1.next.next = ListNode(0)
38+
h1.next.next = ListNode(-4)
39+
h1.next.next.next = h1.next
40+
r1 = sol.hasCycle(h1)
41+
print(f"TC 1 is Passed!" if r1 == True else f"TC 1 is Failed!")
42+
43+
h2 = ListNode(1)
44+
h2.next = ListNode(2)
45+
h2.next.next = h2
46+
r2 = sol.hasCycle(h2)
47+
print(f"TC 2 is Passed!" if r2 == True else f"TC 2 is Failed!")
48+
49+
h3 = ListNode(1)
50+
r3 = sol.hasCycle(h3)
51+
print(f"TC 3 is Passed!" if r3 == False else f"TC 3 is Failed!")
52+
53+
do_test()

maximum-product-subarray/ayosecu.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(nums)
6+
- Space Complexity: O(1)
7+
"""
8+
def maxProduct(self, nums: List[int]) -> int:
9+
max_now, max_prod, min_prod = nums[0], nums[0], nums[0]
10+
11+
for num in nums[1:]:
12+
if num < 0:
13+
# if number is negative, swap the min/max value
14+
max_prod, min_prod = min_prod, max_prod
15+
16+
max_prod = max(num, max_prod * num)
17+
min_prod = min(num, min_prod * num)
18+
max_now = max(max_now, max_prod)
19+
20+
return max_now
21+
22+
tc = [
23+
([2,3,-2,4], 6),
24+
([-2,0,-1], 0)
25+
]
26+
27+
sol = Solution()
28+
for i, (n, e) in enumerate(tc, 1):
29+
r = sol.maxProduct(n)
30+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

minimum-window-substring/ayosecu.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from collections import Counter, defaultdict
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(s)
6+
- Space Complexity: O(m), m = len(t)
7+
"""
8+
def minWindow(self, s: str, t: str) -> str:
9+
need = Counter(t)
10+
need_len = len(need)
11+
win_dic = defaultdict(int)
12+
cnt = 0
13+
min_range, min_len = [-1, -1], float("inf")
14+
15+
l = 0
16+
for r in range(len(s)):
17+
c = s[r]
18+
win_dic[c] += 1
19+
20+
if c in need and win_dic[c] == need[c]:
21+
cnt += 1
22+
23+
while cnt == need_len:
24+
# Update min range
25+
check_len = r - l + 1
26+
if check_len < min_len:
27+
min_range = [l, r]
28+
min_len = check_len
29+
30+
# Move left pointer
31+
win_dic[s[l]] -= 1
32+
if s[l] in need and win_dic[s[l]] < need[s[l]]:
33+
cnt -= 1
34+
l += 1
35+
36+
return s[min_range[0]:min_range[1]+1] if min_len != float("inf") else ""
37+
38+
tc = [
39+
("ADOBECODEBANC", "ABC", "BANC"),
40+
("a", "a", "a"),
41+
("a", "aa", "")
42+
]
43+
44+
sol = Solution()
45+
for i, (s, t, e) in enumerate(tc, 1):
46+
r = sol.minWindow(s, t)
47+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from typing import List
2+
from collections import deque
3+
4+
class Solution:
5+
"""
6+
- Time Complexity: O(mn)
7+
- Space Complexity: O(mn)
8+
"""
9+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
10+
m, n = len(heights), len(heights[0])
11+
12+
# Visit checking for each ocean
13+
p_visited = [[False] * n for _ in range(m)]
14+
a_visited = [[False] * n for _ in range(m)]
15+
16+
def bfs(q, visited):
17+
dir = [(-1, 0), (0, -1), (1, 0), (0, 1)]
18+
while q:
19+
r, c = q.popleft()
20+
for dx, dy in dir:
21+
next_r, next_c = r + dx, c + dy
22+
# checking next cell is not visited and higher than current cell
23+
if ( 0 <= next_r < m and 0 <= next_c < n and not visited[next_r][next_c]
24+
and heights[next_r][next_c] >= heights[r][c] ):
25+
visited[next_r][next_c] = True
26+
q.append((next_r, next_c))
27+
28+
p_dq, a_dq = deque(), deque()
29+
30+
for i in range(m):
31+
# left side (pacific)
32+
p_dq.append((i, 0))
33+
p_visited[i][0] = True
34+
# right side (atlantic)
35+
a_dq.append((i, n - 1))
36+
a_visited[i][n - 1] = True
37+
38+
for j in range(n):
39+
# top side (pacific)
40+
p_dq.append((0, j))
41+
p_visited[0][j] = True
42+
# bottom side (atlantic)
43+
a_dq.append((m - 1, j))
44+
a_visited[m - 1][j] = True
45+
46+
bfs(p_dq, p_visited)
47+
bfs(a_dq, a_visited)
48+
49+
result = []
50+
for i in range(m):
51+
for j in range(n):
52+
if p_visited[i][j] and a_visited[i][j]:
53+
# both of oceans are accessible
54+
result.append([i, j])
55+
56+
return result
57+
58+
tc = [
59+
([[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]], [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]),
60+
([[1]], [[0,0]])
61+
]
62+
63+
sol = Solution()
64+
for i, (h, e) in enumerate(tc, 1):
65+
r = sol.pacificAtlantic(h)
66+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

sum-of-two-integers/ayosecu.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(1), <= 32 bit operation
4+
- Space Complexity: O(1)
5+
"""
6+
def getSum(self, a: int, b: int) -> int:
7+
# Using mask value for making 32 bit integer operation
8+
MASK = 0xFFFFFFFF
9+
MAX_INT = 0x7FFFFFFF
10+
11+
while b != 0:
12+
xor = (a ^ b) & MASK
13+
carry = ((a & b) << 1) & MASK
14+
a, b = xor, carry
15+
16+
# If a is overflow than MAX_INT (Negative Integer), return 2's compliment value
17+
return a if a <= MAX_INT else ~(a ^ MASK)
18+
19+
tc = [
20+
(1, 2, 3),
21+
(2, 3, 5)
22+
]
23+
24+
sol = Solution()
25+
for i, (a, b, e) in enumerate(tc, 1):
26+
r = sol.getSum(a, b)
27+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)