Skip to content

[ayosecu] Week 9 Solutions #1531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions linked-list-cycle/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from typing import Optional

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
"""
- Time Complexity: O(n), n = The number of nodes
- Space Complexity: O(1)
"""
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False

slow, fast = head, head
while slow and fast:
slow = slow.next
if fast.next:
fast = fast.next.next
else:
return False

if fast == slow:
return True

return False

# Run Test Cases
def do_test():
sol = Solution()

h1 = ListNode(3)
h1.next = ListNode(2)
h1.next.next = ListNode(0)
h1.next.next = ListNode(-4)
h1.next.next.next = h1.next
r1 = sol.hasCycle(h1)
print(f"TC 1 is Passed!" if r1 == True else f"TC 1 is Failed!")

h2 = ListNode(1)
h2.next = ListNode(2)
h2.next.next = h2
r2 = sol.hasCycle(h2)
print(f"TC 2 is Passed!" if r2 == True else f"TC 2 is Failed!")

h3 = ListNode(1)
r3 = sol.hasCycle(h3)
print(f"TC 3 is Passed!" if r3 == False else f"TC 3 is Failed!")

do_test()
30 changes: 30 additions & 0 deletions maximum-product-subarray/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from typing import List

class Solution:
"""
- Time Complexity: O(n), n = len(nums)
- Space Complexity: O(1)
"""
def maxProduct(self, nums: List[int]) -> int:
max_now, max_prod, min_prod = nums[0], nums[0], nums[0]

for num in nums[1:]:
if num < 0:
# if number is negative, swap the min/max value
max_prod, min_prod = min_prod, max_prod

max_prod = max(num, max_prod * num)
min_prod = min(num, min_prod * num)
max_now = max(max_now, max_prod)

return max_now

tc = [
([2,3,-2,4], 6),
([-2,0,-1], 0)
]

sol = Solution()
for i, (n, e) in enumerate(tc, 1):
r = sol.maxProduct(n)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
47 changes: 47 additions & 0 deletions minimum-window-substring/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from collections import Counter, defaultdict

class Solution:
"""
- Time Complexity: O(n), n = len(s)
- Space Complexity: O(m), m = len(t)
"""
def minWindow(self, s: str, t: str) -> str:
need = Counter(t)
need_len = len(need)
win_dic = defaultdict(int)
cnt = 0
min_range, min_len = [-1, -1], float("inf")

l = 0
for r in range(len(s)):
c = s[r]
win_dic[c] += 1

if c in need and win_dic[c] == need[c]:
cnt += 1

while cnt == need_len:
# Update min range
check_len = r - l + 1
if check_len < min_len:
min_range = [l, r]
min_len = check_len

# Move left pointer
win_dic[s[l]] -= 1
if s[l] in need and win_dic[s[l]] < need[s[l]]:
cnt -= 1
l += 1

return s[min_range[0]:min_range[1]+1] if min_len != float("inf") else ""

tc = [
("ADOBECODEBANC", "ABC", "BANC"),
("a", "a", "a"),
("a", "aa", "")
]

sol = Solution()
for i, (s, t, e) in enumerate(tc, 1):
r = sol.minWindow(s, t)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
66 changes: 66 additions & 0 deletions pacific-atlantic-water-flow/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from typing import List
from collections import deque

class Solution:
"""
- Time Complexity: O(mn)
- Space Complexity: O(mn)
"""
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])

# Visit checking for each ocean
p_visited = [[False] * n for _ in range(m)]
a_visited = [[False] * n for _ in range(m)]

def bfs(q, visited):
dir = [(-1, 0), (0, -1), (1, 0), (0, 1)]
while q:
r, c = q.popleft()
for dx, dy in dir:
next_r, next_c = r + dx, c + dy
# checking next cell is not visited and higher than current cell
if ( 0 <= next_r < m and 0 <= next_c < n and not visited[next_r][next_c]
and heights[next_r][next_c] >= heights[r][c] ):
visited[next_r][next_c] = True
q.append((next_r, next_c))

p_dq, a_dq = deque(), deque()

for i in range(m):
# left side (pacific)
p_dq.append((i, 0))
p_visited[i][0] = True
# right side (atlantic)
a_dq.append((i, n - 1))
a_visited[i][n - 1] = True

for j in range(n):
# top side (pacific)
p_dq.append((0, j))
p_visited[0][j] = True
# bottom side (atlantic)
a_dq.append((m - 1, j))
a_visited[m - 1][j] = True

bfs(p_dq, p_visited)
bfs(a_dq, a_visited)

result = []
for i in range(m):
for j in range(n):
if p_visited[i][j] and a_visited[i][j]:
# both of oceans are accessible
result.append([i, j])

return result

tc = [
([[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]]),
([[1]], [[0,0]])
]

sol = Solution()
for i, (h, e) in enumerate(tc, 1):
r = sol.pacificAtlantic(h)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
27 changes: 27 additions & 0 deletions sum-of-two-integers/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
"""
- Time Complexity: O(1), <= 32 bit operation
- Space Complexity: O(1)
"""
def getSum(self, a: int, b: int) -> int:
# Using mask value for making 32 bit integer operation
MASK = 0xFFFFFFFF
MAX_INT = 0x7FFFFFFF

while b != 0:
xor = (a ^ b) & MASK
carry = ((a & b) << 1) & MASK
a, b = xor, carry

# If a is overflow than MAX_INT (Negative Integer), return 2's compliment value
return a if a <= MAX_INT else ~(a ^ MASK)

tc = [
(1, 2, 3),
(2, 3, 5)
]

sol = Solution()
for i, (a, b, e) in enumerate(tc, 1):
r = sol.getSum(a, b)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")