Skip to content
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

[jinah92] Week 4 #810

Merged
merged 6 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
10 changes: 10 additions & 0 deletions coin-change/jinah92.py
Copy link
Contributor

Choose a reason for hiding this comment

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

이건 리뷰는 아니고, 제가 coin-change 문제를 풀면서 한가지 고민했던 부분을 공유드립니다. 문제의 예시는 coins 배열이 오름차순으로 주어지지만, 항상 오름차순으로 주어진다는 보장은 없습니다. 만약 coins 가 오름차순으로 주어지지 않더라도 작성하신 코드가 잘작동할지 궁금합니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

다음과 같은 이유로, dp 배열을 갱신하는데 영향을 끼치지 않기 때문에 coins 배열의 정렬 순서는 상관이 없을 것 같습니다

  • 모든 동전을 독립적으로 처리: dp 배열은 각 동전에 대해 독립적으로 갱신됩니다. 즉, coins 배열이 어떤 순서로 주어지더라도, 모든 동전에 대해 동일한 방식으로 dp[i]를 계산합니다.
  • 최소값 비교의 특성: dp[i]는 항상 현재까지 계산된 값(dp[i])과 새로운 값(dp[i−coin]+1) 중 더 작은 값을 선택합니다. 이 과정에서 특정 동전의 순서는 중요하지 않습니다. 모든 동전에 대해 동일한 최솟값 비교가 이루어지므로 결과가 동일하게 유지됩니다.
  • 동전의 중복 사용 허용: 문제에서 각 동전은 여러 번 사용할 수 있습니다. 따라서 특정 동전을 먼저 처리하거나 나중에 처리하더라도 최종 결과에는 영향을 미치지 않습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# O(C*A) times, O(A) spaces
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [0] + [amount + 1] * amount

for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i-coin]+1)

return dp[amount] if dp[amount] < amount + 1 else -1
18 changes: 18 additions & 0 deletions merge-two-sorted-lists/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# O(m+n) times, O(1) spaces
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(None)
node = dummy

while list1 and list2:
if list1.val < list2.val:
node.next = list1
list1 = list1.next
else:
node.next = list2
list2 = list2.next

node = node.next

node.next = list1 or list2
return dummy.next
12 changes: 12 additions & 0 deletions missing-number/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# O(n) times, O(n) spaces
class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums_keys = dict.fromkeys(nums,0)
DaleSeo marked this conversation as resolved.
Show resolved Hide resolved
last = 0

for i in range(len(nums)):
if not i in nums_keys:
return i
last += 1

return last
18 changes: 18 additions & 0 deletions palindromic-substrings/jinah92.py
Copy link
Contributor

Choose a reason for hiding this comment

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

혹시 시간적 여유가 되신다면, 이 코드의 시간 복잡도를 줄여보는 것을 시도해보시면 어떨까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

DP 풀이법 추가했습니다~

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# O((LogN)^N) times, O(1) spaces
DaleSeo marked this conversation as resolved.
Show resolved Hide resolved
class Solution:
def countSubstrings(self, s: str) -> int:
sub_str_len = 1
result = 0

while sub_str_len <= len(s):
start_idx = 0
while start_idx + sub_str_len <= len(s):
sub_str = s[start_idx:start_idx+sub_str_len]
if sub_str == sub_str[::-1]:
result += 1
start_idx += 1

sub_str_len += 1


return result
25 changes: 25 additions & 0 deletions word-search/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# O(M*N*4^W) times, O(M*N+W) spaces
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])
visited = set()
Copy link
Contributor

Choose a reason for hiding this comment

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

visited 배열을 제거하고, 공간복잡도를 조금 더 최적화해보면 어떨까요?

Copy link
Contributor Author

@jinah92 jinah92 Jan 3, 2025

Choose a reason for hiding this comment

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

방문여부를 별도 set으로 관리하지 않고, board에 빈 값을 넣고, 방문 이후에는 원래 값으로 원복하는 방법이 있을 것 같습니다.
따라서 최적한다면 O(W) 공간복잡도로 최적화됩니다.


directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def dfs(row, col, idx):
if idx == len(word):
return True
if not (0 <= row < rows and 0 <= col < cols):
return False
if board[row][col] != word[idx]:
return False
if (row, col) in visited:
return False

visited.add((row, col))
result = any(dfs(row+r, col+c, idx+1) for (r, c) in directions)
visited.remove((row, col))

return result

return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
Loading