Skip to content
Open
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
33 changes: 33 additions & 0 deletions clone-graph/daehyun99.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/daehyun99.py
# Time: O(n)
# Space: O(n)
"""
# 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']:
        have_to_look = set()
        seen = set()
        copied = {}

        have_to_look.add(node)

        while len(have_to_look) > 0 :
            curr = have_to_look.pop()
            if curr is not None:
                if curr.val not in copied:
                    copied[curr.val] = Node(curr.val, None)
                for neighbor in curr.neighbors:
                    if neighbor.val not in copied:
                        copied[neighbor.val] = Node(neighbor.val, None)
                        if neighbor.val not in seen:
                            have_to_look.add(neighbor)
                    copied[curr.val].neighbors.append(copied[neighbor.val])
                seen.add(curr.val)

        return copied.get(1, None)
  • 패턴: Hash Map / Hash Set, Breadth-First Search, Graph
  • 설명: 해당 코드는 그래프 순회를 위해 큐 대신 집합으로 너비를 관리하며, 노드 간 연결 정보 복제(깊은 복제)를 위해 해시 맵/세트를 사용합니다. 그래프의 각 노드를 방문하며 인접 노드를 큐처럼 확장하는 BFS 스타일 로직으로 그래프 복제를 수행합니다.

📊 시간/공간 복잡도 분석

ℹ️ 이 파일에는 2가지 풀이가 포함되어 있어 각각 분석합니다.

풀이 1: Solution.cloneGraph — Time: O(N + E) / Space: O(N)
복잡도
Time O(N + E)
Space O(N)

피드백: 노드 고유 식별자로 val 을 사용해 복제, 해시맵으로 매핑하지만 노드 객체가 중복될 수 있어 실제 구현에서 id 기반 매핑이 더 안전하다.

개선 제안: 고려해볼 만한 대안: 노드 객체 자체를 키로 매핑하고, 각 노드의 객체를 직접 참조하는 방식으로 구현하면 중복 문제를 피할 수 있다.

풀이 2: Solution.cloneGraph — Time: O(N + E) / Space: O(N)
복잡도
Time O(N + E)
Space O(N)

피드백: 현재 구현은 노드 값을 키로 사용해 복제 노드를 저장하지만, 그래프에 같은 값의 노드가 여러 개 있을 수 있는 경우 문제가 생길 수 있다.

개선 제안: 고려해볼 만한 대안: 노드 객체를 직접 키로 사용하고, 깊이/너비 우선 탐색으로 실제 Node 객체 간의 매핑을 유지하도록 재구현.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Time: O(n)

@parkhojeong parkhojeong Aug 15, 2026

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.

시간 복잡도에 노드 뿐 아니라 간선도 포함되어야 할 거 같습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

그렇군요! O(N + E)네요

# Space: O(n)
"""
# 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']:
have_to_look = set()
seen = set()
copied = {}

have_to_look.add(node)

while len(have_to_look) > 0 :
curr = have_to_look.pop()
if curr is not None:
if curr.val not in copied:
copied[curr.val] = Node(curr.val, None)
for neighbor in curr.neighbors:
if neighbor.val not in copied:
copied[neighbor.val] = Node(neighbor.val, None)
if neighbor.val not in seen:
have_to_look.add(neighbor)
copied[curr.val].neighbors.append(copied[neighbor.val])
seen.add(curr.val)

return copied.get(1, None)

59 changes: 59 additions & 0 deletions longest-repeating-character-replacement/daehyun99.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/daehyun99.py
# Time: O(s)
# Space: O(s)
from collections import defaultdict
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        count = defaultdict(int)

        l = 0
        maxf = 0
        res = 0
        for r in range(len(s)):
            count[s[r]] += 1
            maxf = max(maxf, count[s[r]])

            while (r - l + 1) - maxf > k:
                count[s[l]] -= 1
                l += 1
            res = max(res, r - l + 1)
        return res

"""
# Time: O(s)
# Space: O(s)
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        # find_bunch()
        bunch = []
        start_idx = 0
        start_word = s[0]
        for i in range(1, len(s)):
            if s[i] != start_word:
                bunch.append([start_word, i- start_idx])
                start_word = s[i]
                start_idx = i
        bunch.append([start_word, len(s) - start_idx])

        # find_LRCR()
        unique = set([c for c in s])
        result = 0

        for base in unique:
            changed_num = 0
            left = 0
            right = 0
            length = 0
            while right < len(bunch):
                if bunch[right][0] != base:
                    changed_num += bunch[right][1]
                length += bunch[right][1]
                right += 1

                while changed_num > k:
                    if bunch[left][0] != base:
                        changed_num -= bunch[left][1]
                    length -= bunch[left][1]
                    left += 1
                result = max(result, min(length + k - changed_num, len(s)))
        return result
"""
  • 패턴: Sliding Window, Greedy
  • 설명: 코드는 좌우 포인터를 이용해 부분 문자열의 길이를 확장/축소시키는 sliding window 기법과, 최댓값 유지 및 조건 만족 시 최적해를 갱신하는 Greedy 특성을 보입니다. 또한 반복 문자 최대 개수 제약을 통해 필요한 변환 수를 최소화하는 방식이라서 두 패턴이 함께 적용됩니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(1)

피드백: 슬라이딩 윈도우 방식이 최적의 시간 복잡도를 보장하고, 딕셔너리로 문자 빈도를 관리한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Time: O(s)
# Space: O(s)

@parkhojeong parkhojeong Aug 15, 2026

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.

공간 복잡도 표기가 잘못 되어 있네요.

from collections import defaultdict
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = defaultdict(int)

l = 0
maxf = 0
res = 0
for r in range(len(s)):
count[s[r]] += 1
maxf = max(maxf, count[s[r]])

while (r - l + 1) - maxf > k:
count[s[l]] -= 1
l += 1
res = max(res, r - l + 1)
return res

"""
# Time: O(s)
# Space: O(s)
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# find_bunch()
bunch = []
start_idx = 0
start_word = s[0]
for i in range(1, len(s)):
if s[i] != start_word:
bunch.append([start_word, i- start_idx])
start_word = s[i]
start_idx = i
bunch.append([start_word, len(s) - start_idx])

# find_LRCR()
unique = set([c for c in s])
result = 0

for base in unique:
changed_num = 0
left = 0
right = 0
length = 0
while right < len(bunch):
if bunch[right][0] != base:
changed_num += bunch[right][1]
length += bunch[right][1]
right += 1

while changed_num > k:
if bunch[left][0] != base:
changed_num -= bunch[left][1]
length -= bunch[left][1]
left += 1
result = max(result, min(length + k - changed_num, len(s)))
return result
"""
23 changes: 23 additions & 0 deletions palindromic-substrings/daehyun99.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/daehyun99.py
class Solution:
    def countSubstrings(self, s: str) -> int:
        result = 0

        # odd
        for i in range(0, len(s)):
            m, n = i, i
            while 0 <= m and n < len(s) and s[m] == s[n]:
                result += 1
                m -= 1
                n += 1

        # even
        for i in range(0, len(s)-1):
            m, n = i, i+1
            while 0 <= m and n < len(s) and s[m] == s[n]:
                result += 1
                m -= 1
                n += 1
        return result


  • 패턴: Two Pointers, Monotonic Stack, Dynamic Programming
  • 설명: 주어진 코드는 문자열의 부분문자열 팰린드롬을 중앙에서 확장하는 방식으로 모든 팰린드롬을 탐색합니다. 이를 통해 길이에 따라 좌우 포인터를 확장하는 Two Pointers 패턴에 해당하며, 팰린드롬 여부를 +=로 누적하므로 간단한 DP 없이도 해결됩니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n^2)
Space O(1)

피드백: 공간은 상수이며 시간은 모든 중심에서 확장하는 방식으로 계산한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution:
def countSubstrings(self, s: str) -> int:
result = 0

# odd
for i in range(0, len(s)):
m, n = i, i
while 0 <= m and n < len(s) and s[m] == s[n]:
result += 1
m -= 1
n += 1

# even
for i in range(0, len(s)-1):
m, n = i, i+1
while 0 <= m and n < len(s) and s[m] == s[n]:
result += 1
m -= 1
n += 1
return result



7 changes: 7 additions & 0 deletions reverse-bits/daehyun99.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/daehyun99.py
class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for i in range(32):
            bit = (n >> i) & 1
            res += (bit << (31 - i))
        return res
  • 패턴: Bit Manipulation, Divide and Conquer
  • 설명: 주어진 코드는 비트를 앞으로 이동시켜 역순으로 뒤집는 연산으로 비트 조작을 직접 수행한다. 반복적으로 비트를 추출하고 위치를 바꿔 누적하는 방식은 비트 조작 패턴과 특정 구간 간 분할·합치의 아이디어를 활용하는 divide-and-conquer 형태로 볼 수 있다.

📊 시간/공간 복잡도 분석

복잡도
Time O(32)
Space O(1)

피드백: 정수의 각 비트를 순차적으로 뒤집어 최종 값을 구성한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for i in range(32):
bit = (n >> i) & 1
res += (bit << (31 - i))
return res
Loading