Skip to content
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
36 changes: 36 additions & 0 deletions clone-graph/dolphinflow86.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

clone-graph/dolphinflow86.py
# 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)
  • 패턴: Depth-First Search, Hash Map / Hash Set
  • 설명: 그래프의 각 노드를 깊이 우선 탐색으로 방문하며 노드 복제본을 해시맵에 매핑한다. 중복 방문 방지와 그래프 전체 탐색에 해시맵과 재귀 스택을 사용한다.

📊 시간/공간 복잡도 분석

복잡도
Time O(N + E)
Space O(N)

피드백: 딥카피 시 각 노드를 고유 키로 매핑해 중복 생성 없이 그래프를 복제합니다. 이로써 모든 간선은 한 번씩 처리되고, 재방문 방지를 위한 해시맵이 필요합니다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

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)
17 changes: 17 additions & 0 deletions longest-common-subsequence/dolphinflow86.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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]
  • 패턴: Dynamic Programming
  • 설명: 두 문자열의 부분수열 길이를 2D DP 테이블로 구하는 전형적인 다이나믹 프로그래밍 문제로, 각 상태가 부분문자열의 최댓값을 저장하며 점화식으로 해결합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(M * N) O(m * n)
Space O(M * N) O(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]
22 changes: 22 additions & 0 deletions longest-repeating-character-replacement/dolphinflow86.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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
  • 패턴: Sliding Window, Hash Map / Hash Set
  • 설명: 문자 교체 횟수를 최소화하며 윈도우를 확장/축소하는 슬라이딩 윈도우 기법이 핵심이다. 해시 맵으로 문자 빈도를 추적하고, 현재 윈도우의 최대 빈도와 비교해 허용된 교체 수를 초과하면 좌측 포인터를 이동한다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(1) O(Alphabet)

피드백: 윈도우의 길이가 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
23 changes: 23 additions & 0 deletions palindromic-substrings/dolphinflow86.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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
  • 패턴: Two Pointers, Monotonic Stack, Hash Map / Hash Set
  • 설명: 가운데를 중심으로 좌우로 확장하는 방식으로 팰린드롬 부분 문자열을 탐색합니다(센터 확장). 두 가지 중심(같은 문자, 인접한 문자 두 개)에서 확장을 반복하며 부분문자열 개수를 셉니다. 이는 Sliding Window와는 다르고, 중앙 확장 로직으로 두 포인터를 좌우로 이동시키는 패턴에 해당합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N^2) O(n^2)
Space O(1) O(1)

피드백: 각 중심으로 양쪽으로 확장하며 팰린드롬 개수를 누적합니다. 보조 배열 없이 상수 공간으로 구현했습니다.

개선 제안: 현재 구현이 적절해 보입니다.

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
11 changes: 11 additions & 0 deletions reverse-bits/dolphinflow86.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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
  • 패턴: Bit Manipulation
  • 설명: 주어진 코드는 비트를 추출하고 재배치하여 비트 역순을 만드므로 Bit Manipulation 패턴에 해당합니다. 고정된 반복(32회)로 비트를 시프트/비트연산으로 처리합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(1) O(32)
Space O(1) O(1)

피드백: 고정된 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
Loading