Skip to content

[Helena] Week 7 #936

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
Jan 25, 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
24 changes: 24 additions & 0 deletions longest-substring-without-repeating-characters/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Time Complexity: O(n): both pointers (left and right) traverse the string once.
# Space Complexity: O(n): worst case, all characters are unique, so the set will store all characters.

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# to store characters in the current window
window_set = set()
Copy link
Member

@dusunax dusunax Jan 24, 2025

Choose a reason for hiding this comment

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

고생하셨습니다!
Set 자료구조를 사용하면 worst case시 공간 복잡도가 O(n)이 되는데
ASCII 배열을 사용해서 O(1)으로 개선하는 방향에 대해서 @ekgns33님께 리뷰를 받아서 함께 공유 드립니다🙂

부분문자열에서 각 문자는 1회만 등장할 수 있다는 조건때문에 Set을 선택하셨군요. 👍
문자의 범위가 명확하게 정의되어 있다면 (e.g ASCII) 배열을 사용할 수도 있을 것 같아요!

아래 문제도 추가적으로 풀어보시면 sliding window 패턴을 익히시는데 도움이 될 것 같습니다
https://leetcode.com/problems/substring-with-concatenation-of-all-words

Originally posted by @ekgns33 in #935 (comment)

# to store the max length of a substring
max_length = 0
# left pointer for the sliding window
left = 0

# iterate through each char in the string using the right pointer
for right in range(len(s)):
# if the char is already in the window, shrink the window
while s[right] in window_set:
window_set.remove(s[left]) # remove the leftmost char
left += 1 # move the left pointer to the right
# add the new char
window_set.add(s[right])
# update the max length if the current window is longer
max_length = max(max_length, right - left + 1)

return max_length
30 changes: 30 additions & 0 deletions number-of-islands/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Time Complexity: O(N * M), where N is the number of rows and M is the number of columns.
# Space Complexity: O(N * M), in the worst case if the grid is entirely land.

class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# get the number of rows and columns in the grid
rows, cols = len(grid), len(grid[0])

# define a dfs function to mark visited cells
def dfs(i, j):
# if out of bounds or the cell is water, stop here
if i < 0 or i >= rows or j < 0 or j >= cols or grid[i][j] == "0":
return True

# mark the current cell as visited by changing "1" to "0"
grid[i][j] = "0"

# visit recursively all neighboring cells
return True if (dfs(i - 1, j) and dfs(i + 1, j) and dfs(i, j - 1) and dfs(i, j + 1)) else False

count = 0
# loop through the entire grid to find islands
for i in range(rows):
for j in range(cols):
# if we find land ("1"), start a dfs
if grid[i][j] == "1":
# increment count if dfs confirms a new island
if dfs(i, j):
count += 1
return count
14 changes: 14 additions & 0 deletions reverse-linked-list/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Time Complexity: O(n)
# Space Complexity: O(1)

class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
# to traverse the original list, starting from head
current = head
while current:
# reverse the link and move to the next node
prev, prev.next, current = current, prev, current.next

# prev is now the head of the reversed list
return prev
34 changes: 34 additions & 0 deletions set-matrix-zeroes/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Time Complexity: O(m * n) - iterate through the matrix multiple times.
# Space Complexity: O(1) - no extra space is used apart from variables.

class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
m, n = len(matrix), len(matrix[0])

# check if the first row contains any zero
first_row_zero = any(matrix[0][j] == 0 for j in range(n))
# check if the first column contains any zero
first_col_zero = any(matrix[i][0] == 0 for i in range(m))

# use the first row and column to mark zero
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0

# update the matrix using the marks from the first row and column
for i in range(1, m):
for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0

# handle the first row separately if it initially had any zero
if first_row_zero:
for j in range(n):
matrix[0][j] = 0

# handle the first column separately if it initially had any zero
if first_col_zero:
for i in range(m):
matrix[i][0] = 0
22 changes: 22 additions & 0 deletions unique-paths/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Time Complexity: O(N * M) : iterate through a grid of size m x n once.
# Space Complexity: O(N * M) : use a DP table of size (m+1) x (n+1) to store the number of paths.

class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# create a dp table and add extra rows and columns for easier indexing
table = [[0 for x in range(n+1)] for y in range(m+1)]

# set the starting point, one way to be at the start
table[1][1] = 1

# iterate the grid to calculate paths
for i in range(1, m+1):
for j in range(1, n+1):
# add paths going down
if i+1 <= m:
table[i+1][j] += table[i][j]
# add paths going right
if j+1 <= n:
table[i][j+1] += table[i][j]

return table[m][n]
Loading