Skip to content

Commit 7f0d45c

Browse files
authored
Merge pull request #1469 from ayosecu/main
[ayosecu] Week 07 Solutions
2 parents 51f1e1e + 4e58a77 commit 7f0d45c

File tree

5 files changed

+199
-0
lines changed

5 files changed

+199
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(n), n = len(s)
4+
- Space Complexity: O(n)
5+
"""
6+
def lengthOfLongestSubstring(self, s: str) -> int:
7+
check_set = set()
8+
9+
longest_length, length = 0, 0
10+
l, r = 0, 0
11+
while r < len(s):
12+
# check each character (s[r]) is duplicated, and expand or narrow the length
13+
if s[r] not in check_set:
14+
check_set.add(s[r])
15+
length += 1
16+
longest_length = max(longest_length, length)
17+
r += 1
18+
else:
19+
check_set.remove(s[l])
20+
length -= 1
21+
l += 1
22+
23+
return longest_length
24+
25+
tc = [
26+
("abcabcbb", 3),
27+
("bbbbb", 1),
28+
("pwwkew", 3)
29+
]
30+
31+
sol = Solution()
32+
for i, (s, e) in enumerate(tc, 1):
33+
r = sol.lengthOfLongestSubstring(s)
34+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

number-of-islands/ayosecu.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(N), N = The number of items = len(grid) * len(grid[0])
6+
- Space Complexity: O(N)
7+
- In worst case (all "1"s), The depth of dfs is N => O(N)
8+
"""
9+
def numIslands(self, grid: List[List[str]]) -> int:
10+
m, n = len(grid), len(grid[0])
11+
12+
def dfs(i, j):
13+
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != "1":
14+
return
15+
16+
grid[i][j] = "#" # Visited
17+
for dx, dy in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
18+
dfs(i + dx, j + dy)
19+
20+
count = 0
21+
for i in range(m):
22+
for j in range(n):
23+
if grid[i][j] == "1":
24+
count += 1
25+
dfs(i, j)
26+
27+
return count
28+
29+
tc = [
30+
([
31+
["1","1","1","1","0"],
32+
["1","1","0","1","0"],
33+
["1","1","0","0","0"],
34+
["0","0","0","0","0"]
35+
], 1),
36+
([
37+
["1","1","0","0","0"],
38+
["1","1","0","0","0"],
39+
["0","0","1","0","0"],
40+
["0","0","0","1","1"]
41+
], 3)
42+
]
43+
44+
sol = Solution()
45+
for i, (grid, e) in enumerate(tc, 1):
46+
r = sol.numIslands(grid)
47+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

reverse-linked-list/ayosecu.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import Optional
2+
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(n), n = The number of nodes.
12+
- Space Complexity: O(1)
13+
"""
14+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
15+
pre = None
16+
while head:
17+
nxt = head.next
18+
head.next = pre
19+
pre = head
20+
head = nxt
21+
22+
return pre
23+
24+
def toLinkedList(lists):
25+
dummy = ListNode(-1)
26+
ptr = dummy
27+
for item in lists:
28+
ptr.next = ListNode(item)
29+
ptr = ptr.next
30+
return dummy.next
31+
32+
def toList(head):
33+
result = []
34+
35+
while head:
36+
result.append(head.val)
37+
head = head.next
38+
39+
return result
40+
41+
tc = [
42+
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]),
43+
([1, 2], [2, 1]),
44+
([], [])
45+
]
46+
47+
sol = Solution()
48+
for i, (l, e) in enumerate(tc, 1):
49+
r = toList(sol.reverseList(toLinkedList(l)))
50+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

set-matrix-zeroes/ayosecu.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(mn), m = len(matrix), n = len(matrix[0])
6+
- Space Complexity: O(1)
7+
"""
8+
def setZeroes(self, matrix: List[List[int]]) -> None:
9+
"""
10+
Do not return anything, modify matrix in-place instead.
11+
"""
12+
m = len(matrix)
13+
n = len(matrix[0])
14+
15+
# Update row and column with a flag (infinite) if the value is not zero
16+
def updateRowCol(i, j):
17+
for k in range(m):
18+
if matrix[k][j] != 0:
19+
matrix[k][j] = float("inf")
20+
for k in range(n):
21+
if matrix[i][k] != 0:
22+
matrix[i][k] = float("inf")
23+
24+
# Visit all and update row and column if the value is zero
25+
for i in range(m):
26+
for j in range(n):
27+
if matrix[i][j] == 0:
28+
updateRowCol(i, j)
29+
30+
# Update flagged data to zero
31+
for i in range(m):
32+
for j in range(n):
33+
if matrix[i][j] == float("inf"):
34+
matrix[i][j] = 0
35+
36+
tc = [
37+
([[1,1,1],[1,0,1],[1,1,1]], [[1,0,1],[0,0,0],[1,0,1]]),
38+
([[0,1,2,0],[3,4,5,2],[1,3,1,5]], [[0,0,0,0],[0,4,5,0],[0,3,1,0]])
39+
]
40+
41+
sol = Solution()
42+
for i, (m, e) in enumerate(tc, 1):
43+
sol.setZeroes(m)
44+
print(f"TC {i} is Passed!" if m == e else f"TC {i} is Failed! - Expected: {e}, Result: {m}")

unique-paths/ayosecu.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(mn)
4+
- Space Complexity: O(mn), the "dp" variable
5+
"""
6+
def uniquePaths(self, m: int, n: int) -> int:
7+
dp = [ [1] * n for _ in range(m) ]
8+
9+
# DP Approach
10+
for i in range(1, m):
11+
for j in range(1, n):
12+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
13+
14+
return dp[-1][-1]
15+
16+
tc = [
17+
(3, 7, 28),
18+
(3, 2, 3)
19+
]
20+
21+
sol = Solution()
22+
for i, (m, n, e) in enumerate(tc, 1):
23+
r = sol.uniquePaths(m, n)
24+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)