Repository navigation
[dolphinflow86] WEEK 15 Solutions #2878
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
b513918
241d0a4
aa90347
6c67085
52c33e9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
|
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. 🏷️ 알고리즘 패턴 분석construct-binary-tree-from-preorder-and-inorder-traversal/dolphinflow86.py# N is the number of nodes in the binary tree.
# TC: O(N) - building hashmap takes O(N), and each node is visited once in O(1) time
# SC: O(N) - hashmap takes O(N) space, and recursion call stack takes O(H) up to O(N)
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
inorder_map = {val: idx for idx, val in enumerate(inorder)}
preorder_idx = 0
def build(left: int, right: int) -> Optional[TreeNode]:
nonlocal preorder_idx
if left > right:
return None
root_val = preorder[preorder_idx]
root = TreeNode(root_val)
preorder_idx += 1
mid = inorder_map[root_val]
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)
return root
return build(0, len(inorder) - 1)
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # N is the number of nodes in the binary tree. | ||
| # TC: O(N) - building hashmap takes O(N), and each node is visited once in O(1) time | ||
| # SC: O(N) - hashmap takes O(N) space, and recursion call stack takes O(H) up to O(N) | ||
|
|
||
| from typing import List, Optional | ||
|
|
||
|
|
||
| # Definition for a binary tree node. | ||
| class TreeNode: | ||
|
|
||
| def __init__(self, val=0, left=None, right=None): | ||
| self.val = val | ||
| self.left = left | ||
| self.right = right | ||
|
|
||
|
|
||
| class Solution: | ||
|
|
||
| def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: | ||
| inorder_map = {val: idx for idx, val in enumerate(inorder)} | ||
| preorder_idx = 0 | ||
|
|
||
| def build(left: int, right: int) -> Optional[TreeNode]: | ||
| nonlocal preorder_idx | ||
|
|
||
| if left > right: | ||
| return None | ||
|
|
||
| root_val = preorder[preorder_idx] | ||
| root = TreeNode(root_val) | ||
| preorder_idx += 1 | ||
|
|
||
| mid = inorder_map[root_val] | ||
|
|
||
| root.left = build(left, mid - 1) | ||
| root.right = build(mid + 1, right) | ||
|
|
||
| return root | ||
|
|
||
| return build(0, len(inorder) - 1) |
|
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-palindromic-substring/dolphinflow86.py# N is the length of the string s.
# TC: O(N^2) - expanding around each of the 2N - 1 possible centers takes up to O(N)
# SC: O(1) - constant auxiliary space tracking the start index and maximum length
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) <= 1:
return s
start, max_len = 0, 0
def expand(left: int, right: int) -> tuple[int, int]:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return left + 1, right - left - 1
for i in range(len(s)):
# Odd length palindrome (center is i)
l1, len1 = expand(i, i)
if len1 > max_len:
start, max_len = l1, len1
# Even length palindrome (center is between i and i + 1)
l2, len2 = expand(i, i + 1)
if len2 > max_len:
start, max_len = l2, len2
return s[start:start + max_len]
📊 시간/공간 복잡도 분석
피드백: 중심 확장을 통해 모든 가능한 회문을 검사하므로 전체 시간 복잡도는 문자열 길이의 제곱에 비례합니다. 추가 공간은 상수 공간입니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| # N is the length of the string s. | ||
| # TC: O(N^2) - expanding around each of the 2N - 1 possible centers takes up to O(N) | ||
| # SC: O(1) - constant auxiliary space tracking the start index and maximum length | ||
|
|
||
|
|
||
| class Solution: | ||
|
|
||
| def longestPalindrome(self, s: str) -> str: | ||
| if len(s) <= 1: | ||
| return s | ||
|
|
||
| start, max_len = 0, 0 | ||
|
|
||
| def expand(left: int, right: int) -> tuple[int, int]: | ||
| while left >= 0 and right < len(s) and s[left] == s[right]: | ||
| left -= 1 | ||
| right += 1 | ||
| return left + 1, right - left - 1 | ||
|
|
||
| for i in range(len(s)): | ||
| # Odd length palindrome (center is i) | ||
| l1, len1 = expand(i, i) | ||
| if len1 > max_len: | ||
| start, max_len = l1, len1 | ||
|
|
||
| # Even length palindrome (center is between i and i + 1) | ||
| l2, len2 = expand(i, i + 1) | ||
| if len2 > max_len: | ||
| start, max_len = l2, len2 | ||
|
|
||
| return s[start:start + max_len] |
|
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. 🏷️ 알고리즘 패턴 분석rotate-image/dolphinflow86.py# N is the number of rows and columns in the matrix.
# TC: O(N^2) - reversing rows takes O(N^2) and transposing across diagonal takes O(N^2)
# SC: O(1) - in-place rotation with no extra memory allocation
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# 1. Flip vertically (reverse rows)
matrix.reverse()
# 2. Transpose across main diagonal
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
📊 시간/공간 복잡도 분석
피드백: 두 단계 모두 전체 행렬의 모든 원소를 한 번씩 다루므로 시간은 O(n^2), 추가 공간은 상수입니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # N is the number of rows and columns in the matrix. | ||
| # TC: O(N^2) - reversing rows takes O(N^2) and transposing across diagonal takes O(N^2) | ||
| # SC: O(1) - in-place rotation with no extra memory allocation | ||
|
|
||
| from typing import List | ||
|
|
||
|
|
||
| class Solution: | ||
|
|
||
| def rotate(self, matrix: List[List[int]]) -> None: | ||
| """ | ||
| Do not return anything, modify matrix in-place instead. | ||
| """ | ||
| # 1. Flip vertically (reverse rows) | ||
| matrix.reverse() | ||
|
|
||
| # 2. Transpose across main diagonal | ||
| n = len(matrix) | ||
| for i in range(n): | ||
| for j in range(i + 1, n): | ||
| matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] |
|
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. 🏷️ 알고리즘 패턴 분석subtree-of-another-tree/dolphinflow86.py# M and N are the number of nodes in root and subRoot trees respectively.
# TC: O(M * N) - in the worst case, is_same is checked for every node in root
# SC: O(H) - recursion stack memory bounded by the height of root tree (up to O(M))
from typing import Optional
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional["TreeNode"], subRoot: Optional["TreeNode"]) -> bool:
if not subRoot:
return True
if not root:
return False
def is_same(s: Optional["TreeNode"], t: Optional["TreeNode"]) -> bool:
if not s and not t:
return True
if not s or not t or s.val != t.val:
return False
return is_same(s.left, t.left) and is_same(s.right, t.right)
if is_same(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
📊 시간/공간 복잡도 분석
피드백: 브루트의 모든 노드에 대해 서브트리 비교를 수행하므로 최악의 경우 O(n*m) 시간, 재귀 깊이는 트리의 높이에 비례하는 공간을 사용합니다. 개선 제안: 검색 최적화를 위해 문자열화 비교나 해시를 활용한 방법으로 개선 가능.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # M and N are the number of nodes in root and subRoot trees respectively. | ||
| # TC: O(M * N) - in the worst case, is_same is checked for every node in root | ||
| # SC: O(H) - recursion stack memory bounded by the height of root tree (up to O(M)) | ||
|
|
||
| from typing import Optional | ||
|
|
||
|
|
||
| # Definition for a binary tree node. | ||
| # class TreeNode: | ||
| # def __init__(self, val=0, left=None, right=None): | ||
| # self.val = val | ||
| # self.left = left | ||
| # self.right = right | ||
|
|
||
|
|
||
| class Solution: | ||
|
|
||
| def isSubtree(self, root: Optional["TreeNode"], subRoot: Optional["TreeNode"]) -> bool: | ||
| if not subRoot: | ||
| return True | ||
| if not root: | ||
| return False | ||
|
|
||
| def is_same(s: Optional["TreeNode"], t: Optional["TreeNode"]) -> bool: | ||
| if not s and not t: | ||
| return True | ||
| if not s or not t or s.val != t.val: | ||
| return False | ||
| return is_same(s.left, t.left) and is_same(s.right, t.right) | ||
|
|
||
| if is_same(root, subRoot): | ||
| return True | ||
|
|
||
| return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) |
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.
🏷️ 알고리즘 패턴 분석
alien-dictionary/dolphinflow86.py
📊 시간/공간 복잡도 분석
풀이 1:
Solution.alienOrder— Time: O(C) / Space: O(U + E)피드백: 모든 문자에 대해 간선과 진입차수를 계산하고, 위상정렬로 결과를 얻는다. 유효하지 않은 경우 빈 문자열을 반환한다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2:
Solution.buildTree— Time: O(N) / Space: O(N)피드백: 사전 순회 인덱스를 전역처럼 다루며 inorder 맵을 이용해 루트 위치를 빠르게 찾는다.
개선 제안: 현재 구현이 적절해 보입니다.