Skip to content

[ayosecu] Week 6 solutions #1435

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 10, 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
31 changes: 31 additions & 0 deletions container-with-most-water/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from typing import List

class Solution:
"""
- Time Complexity: O(n), n = len(height)
- Space Complexity: O(1)
"""
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
max_area = float("-inf")

while l < r:
area = (r - l) * min(height[l], height[r])
max_area = max(max_area, area)
if height[l] < height[r]:
l += 1
else:
r -= 1

return max_area

tc = [
([1,8,6,2,5,4,8,3,7], 49),
([1,1], 1),
([0, 1], 0)
]

sol = Solution()
for i, (h, e) in enumerate(tc, 1):
r = sol.maxArea(h)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
63 changes: 63 additions & 0 deletions design-add-and-search-words-data-structure/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
class Trie:
def __init__(self, ch):
self.ch = ch
self.child = {}
self.isEnd = False

class WordDictionary:
def __init__(self):
self.root = Trie("")

"""
- Time Complexity: O(n), n = len(word)
- Space Complexity: O(n)
"""
def addWord(self, word: str) -> None:
cur = self.root
for c in word:
if c not in cur.child:
cur.child[c] = Trie(c)
cur = cur.child[c]
cur.isEnd = True

"""
- Time Complexity
- Without dot(.): O(n), n = len(word)
- With dot(.): O(26^d), d = The number of dots
- Space Complexity: O(n), n = len(word)
"""
def search(self, word: str) -> bool:

def dfs(node, idx):
if len(word) == idx:
return node.isEnd

c = word[idx]
if c == ".":
for child in node.child.values():
if dfs(child, idx + 1):
return True
return False
else:
if c in node.child:
return dfs(node.child[c], idx + 1)
else:
return False

return dfs(self.root, 0)

def doTest():
wd = WordDictionary()
wd.addWord("bad");
wd.addWord("dad");
wd.addWord("mad");
assert wd.search("pad") == False, "Test Case Failed! - search('pad')"
print("Test Case Passed! - search('pad')")
assert wd.search("bad") == True, "Test Case Failed! - search('bad')"
print("Test Case Passed! - search('bad')")
assert wd.search(".ad") == True, "Test Case Failed! - search('.ad')"
print("Test Case Passed! - search('.ad')")
assert wd.search("b..") == True, "Test Case Failed! - search('b..')"
print("Test Case Passed! - search('b..')")

doTest()
27 changes: 27 additions & 0 deletions longest-increasing-subsequence/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import List

class Solution:
"""
- Time Complexity: O(n^2), n = len(nums)
- Space Complexity: O(n)
"""
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [1] * len(nums)

for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)

return max(dp)

tc = [
([10,9,2,5,3,7,101,18], 4),
([0,1,0,3,2,3], 4),
([7,7,7,7,7,7,7], 1)
]

sol = Solution()
for i, (nums, e) in enumerate(tc, 1):
r = sol.lengthOfLIS(nums)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
32 changes: 32 additions & 0 deletions spiral-matrix/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import List

class Solution:
"""
- Time Complexity: O(N), N = len(matrix) * len(matrix[0])
- Space Complexity: O(1), If output variable (result) excluded.
"""
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []

while matrix:
result += matrix.pop(0) # append a top row
if matrix and matrix[0]:
for row in matrix:
result.append(row.pop()) # append elements in right side (down direction)
if matrix:
result += matrix.pop()[::-1] # append a bottom row with reversed
if matrix and matrix[0]:
for row in matrix[::-1]:
result.append(row.pop(0)) # append elements in left side (up direction)

return result

tc = [
([[1,2,3],[4,5,6],[7,8,9]], [1,2,3,6,9,8,7,4,5]),
([[1,2,3,4],[5,6,7,8],[9,10,11,12]], [1,2,3,4,8,12,11,10,9,5,6,7])
]

sol = Solution()
for i, (m, e) in enumerate(tc, 1):
r = sol.spiralOrder(m)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
38 changes: 38 additions & 0 deletions valid-parentheses/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution:
"""
- Time Complexity: O(n), n = len(s)
- Space Complexity: O(n)
"""
def isValid(self, s: str) -> bool:
open_ch = { "(":")", "{":"}", "[":"]" }
close_ch = { ")":"(", "}":"{", "]":"[" }
st = []

for c in s:
if c in open_ch:
st.append(c)
elif c in close_ch:
if not st:
return False

if close_ch[c] != st[-1]:
return False
else:
st.pop()
else:
# Error Cases (Invalid Input)
return False

return len(st) == 0

tc = [
("()", True),
("()[]{}", True),
("(]", False),
("([])", True)
]

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