-
-
Notifications
You must be signed in to change notification settings - Fork 361
[dolphinflow86] WEEK 08 Solutions #2815
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
Changes from all commits
ec64a37
3ae2558
4a7a737
0c5f1a4
c48a7a0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # N is the number of nodes, and E is the number of edges. | ||
| # TC: O(N + E) - visits each node and edge once | ||
| # SC: O(N) - uses a hash map for cloned nodes and the recursion stack | ||
|
|
||
| """ | ||
| # Definition for a Node. | ||
| class Node: | ||
| def __init__(self, val = 0, neighbors = None): | ||
| self.val = val | ||
| self.neighbors = neighbors if neighbors is not None else [] | ||
| """ | ||
|
|
||
| from typing import Optional | ||
|
|
||
|
|
||
| class Solution: | ||
|
|
||
| def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: | ||
| if not node: | ||
| return None | ||
|
|
||
| cloned = {} | ||
|
|
||
| def dfs(curr): | ||
| if curr in cloned: | ||
| return cloned[curr] | ||
|
|
||
| copy = Node(curr.val) | ||
| cloned[curr] = copy | ||
|
|
||
| for neighbor in curr.neighbors: | ||
| copy.neighbors.append(dfs(neighbor)) | ||
|
|
||
| return copy | ||
|
|
||
| return dfs(node) |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석longest-common-subsequence/dolphinflow86.py# M is the length of text1, and N is the length of text2.
# TC: O(M * N) - fills a 2D DP table of size (M+1) x (N+1)
# SC: O(M * N) - uses a 2D array to store intermediate DP values
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
📊 시간/공간 복잡도 분석
피드백: 2D DP 배열을 사용해 모든 부분문자열 쌍에 대한 최장 부분수열 길이를 누적적으로 구합니다. 개선 제안: 메모리 사용을 줄이려면 행 하나씩만 유지하는 최적화가 가능하지만, 이해도와 일반성 측면에서 현재 구현이 적절합니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # M is the length of text1, and N is the length of text2. | ||
| # TC: O(M * N) - fills a 2D DP table of size (M+1) x (N+1) | ||
| # SC: O(M * N) - uses a 2D array to store intermediate DP values | ||
| class Solution: | ||
|
|
||
| def longestCommonSubsequence(self, text1: str, text2: str) -> int: | ||
| m, n = len(text1), len(text2) | ||
| dp = [[0] * (n + 1) for _ in range(m + 1)] | ||
|
|
||
| for i in range(1, m + 1): | ||
| for j in range(1, n + 1): | ||
| if text1[i - 1] == text2[j - 1]: | ||
| dp[i][j] = dp[i - 1][j - 1] + 1 | ||
| else: | ||
| dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) | ||
|
|
||
| return dp[m][n] |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석longest-repeating-character-replacement/dolphinflow86.py# N is the length of string s, and K is the allowed replacements.
# TC: O(N) - single pass with sliding window
# SC: O(1) - hash table stores at most 26 uppercase English letters
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = {}
max_freq = 0
left = 0
max_length = 0
for right in range(len(s)):
count[s[right]] = count.get(s[right], 0) + 1
max_freq = max(max_freq, count[s[right]])
while (right - left + 1) - max_freq > k:
count[s[left]] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
📊 시간/공간 복잡도 분석
피드백: 윈도우의 길이가 k 교체 조건을 만족하는지 확인하며 최댓값을 갱신합니다. 해시맵으로 문자별 빈도수를 추적합니다. 개선 제안: 현재 구현이 적절해 보입니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # N is the length of string s, and K is the allowed replacements. | ||
| # TC: O(N) - single pass with sliding window | ||
| # SC: O(1) - hash table stores at most 26 uppercase English letters | ||
| class Solution: | ||
|
|
||
| def characterReplacement(self, s: str, k: int) -> int: | ||
| count = {} | ||
| max_freq = 0 | ||
| left = 0 | ||
| max_length = 0 | ||
|
|
||
| for right in range(len(s)): | ||
| count[s[right]] = count.get(s[right], 0) + 1 | ||
| max_freq = max(max_freq, count[s[right]]) | ||
|
|
||
| while (right - left + 1) - max_freq > k: | ||
| count[s[left]] -= 1 | ||
| left += 1 | ||
|
|
||
| max_length = max(max_length, right - left + 1) | ||
|
|
||
| return max_length |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석palindromic-substrings/dolphinflow86.py# N is the length of string s.
# TC: O(N^2) - expands around each center (2N - 1 possible centers)
# SC: O(1) - uses only constant extra space
class Solution:
def expand_around_center(self, s: str, left: int, right: int) -> int:
sub_count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
sub_count += 1
left -= 1
right += 1
return sub_count
def countSubstrings(self, s: str) -> int:
count = 0
for i in range(len(s)):
count += self.expand_around_center(s, i, i)
count += self.expand_around_center(s, i, i + 1)
return count
📊 시간/공간 복잡도 분석
피드백: 각 중심으로 양쪽으로 확장하며 팰린드롬 개수를 누적합니다. 보조 배열 없이 상수 공간으로 구현했습니다. 개선 제안: 현재 구현이 적절해 보입니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # N is the length of string s. | ||
| # TC: O(N^2) - expands around each center (2N - 1 possible centers) | ||
| # SC: O(1) - uses only constant extra space | ||
| class Solution: | ||
|
|
||
| def expand_around_center(self, s: str, left: int, right: int) -> int: | ||
| sub_count = 0 | ||
|
|
||
| while left >= 0 and right < len(s) and s[left] == s[right]: | ||
| sub_count += 1 | ||
| left -= 1 | ||
| right += 1 | ||
|
|
||
| return sub_count | ||
|
|
||
| def countSubstrings(self, s: str) -> int: | ||
| count = 0 | ||
|
|
||
| for i in range(len(s)): | ||
| count += self.expand_around_center(s, i, i) | ||
| count += self.expand_around_center(s, i, i + 1) | ||
|
|
||
| return count |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석reverse-bits/dolphinflow86.py# 1) Iterate 32 times, getting the last bit of n and putting it to res using bitwise operators.
# TC: O(1)
# SC: O(1)
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
bit = n & 1
res = (res << 1) | bit
n >>= 1
return res
📊 시간/공간 복잡도 분석
피드백: 고정된 32비트 순서를 따라 비트를 반전시키는 간단한 루프 방식입니다. 개선 제안: 현재 구현이 적절해 보입니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| # 1) Iterate 32 times, getting the last bit of n and putting it to res using bitwise operators. | ||
| # TC: O(1) | ||
| # SC: O(1) | ||
| class Solution: | ||
| def reverseBits(self, n: int) -> int: | ||
| res = 0 | ||
| for _ in range(32): | ||
| bit = n & 1 | ||
| res = (res << 1) | bit | ||
| n >>= 1 | ||
| return res |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🏷️ 알고리즘 패턴 분석
clone-graph/dolphinflow86.py
📊 시간/공간 복잡도 분석
피드백: 딥카피 시 각 노드를 고유 키로 매핑해 중복 생성 없이 그래프를 복제합니다. 이로써 모든 간선은 한 번씩 처리되고, 재방문 방지를 위한 해시맵이 필요합니다.
개선 제안: 현재 구현이 적절해 보입니다.