Skip to content

[ayosecu] Week 07 Solutions #1469

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 15, 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
34 changes: 34 additions & 0 deletions longest-substring-without-repeating-characters/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
"""
- Time Complexity: O(n), n = len(s)
- Space Complexity: O(n)
"""
def lengthOfLongestSubstring(self, s: str) -> int:
check_set = set()

longest_length, length = 0, 0
l, r = 0, 0
while r < len(s):
# check each character (s[r]) is duplicated, and expand or narrow the length
if s[r] not in check_set:
check_set.add(s[r])
length += 1
longest_length = max(longest_length, length)
r += 1
else:
check_set.remove(s[l])
length -= 1
l += 1

return longest_length

tc = [
("abcabcbb", 3),
("bbbbb", 1),
("pwwkew", 3)
]

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ayosecu 님 안녕하세요!
저는 딕셔너리를 활용해서 풀었는데, 이 방식이 조금 더 직관적인 것처럼 느껴졌습니다. 좋은 풀이법 알려주셔서 감사합니다!

47 changes: 47 additions & 0 deletions number-of-islands/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from typing import List

class Solution:
"""
- Time Complexity: O(N), N = The number of items = len(grid) * len(grid[0])
- Space Complexity: O(N)
- In worst case (all "1"s), The depth of dfs is N => O(N)
"""
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])

def dfs(i, j):
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != "1":
return

grid[i][j] = "#" # Visited
for dx, dy in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
dfs(i + dx, j + dy)

count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == "1":
count += 1
dfs(i, j)

return count

tc = [
([
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
], 1),
([
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
], 3)
]

sol = Solution()
for i, (grid, e) in enumerate(tc, 1):
r = sol.numIslands(grid)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
50 changes: 50 additions & 0 deletions reverse-linked-list/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import Optional

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

class Solution:
"""
- Time Complexity: O(n), n = The number of nodes.
- Space Complexity: O(1)
"""
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
while head:
nxt = head.next
head.next = pre
pre = head
head = nxt

return pre

def toLinkedList(lists):
dummy = ListNode(-1)
ptr = dummy
for item in lists:
ptr.next = ListNode(item)
ptr = ptr.next
return dummy.next

def toList(head):
result = []

while head:
result.append(head.val)
head = head.next

return result

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

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

class Solution:
"""
- Time Complexity: O(mn), m = len(matrix), n = len(matrix[0])
- Space Complexity: O(1)
"""
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])

# Update row and column with a flag (infinite) if the value is not zero
def updateRowCol(i, j):
for k in range(m):
if matrix[k][j] != 0:
matrix[k][j] = float("inf")
for k in range(n):
if matrix[i][k] != 0:
matrix[i][k] = float("inf")

# Visit all and update row and column if the value is zero
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
updateRowCol(i, j)

# Update flagged data to zero
for i in range(m):
for j in range(n):
if matrix[i][j] == float("inf"):
matrix[i][j] = 0

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

sol = Solution()
for i, (m, e) in enumerate(tc, 1):
sol.setZeroes(m)
print(f"TC {i} is Passed!" if m == e else f"TC {i} is Failed! - Expected: {e}, Result: {m}")
24 changes: 24 additions & 0 deletions unique-paths/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution:
"""
- Time Complexity: O(mn)
- Space Complexity: O(mn), the "dp" variable
"""
def uniquePaths(self, m: int, n: int) -> int:
dp = [ [1] * n for _ in range(m) ]

# DP Approach
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

return dp[-1][-1]

tc = [
(3, 7, 28),
(3, 2, 3)
]

sol = Solution()
for i, (m, n, e) in enumerate(tc, 1):
r = sol.uniquePaths(m, n)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이전에도 느꼈지만, @ayosecu 님 코드는 항상 간결하고 이해하기 쉬운 것 같습니다. DP 풀이가 참고가 되었습니다!
조금 이르지만 approve 하겠습니다. 이번 주도 고생하셨습니다 😊💪