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
31 changes: 31 additions & 0 deletions clone-graph/parkhojeong.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/parkhojeong.py
"""
# 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']:

        visited = {}

        def deep_copy(node):
            if node is None:
                return None

            cur = Node(node.val)
            visited[node.val] = cur

            cur.val = node.val
            for neighbor in node.neighbors:
                if neighbor.val in visited:
                    cur.neighbors.append(visited[neighbor.val])
                else:
                    cur.neighbors.append(deep_copy(neighbor))

            return cur

        return deep_copy(node)
  • 패턴: Depth-First Search, Hash Map / Hash Set, Graph
  • 설명: 그래프의 깊은 복사를 재귀로 수행하며 방문 기록을 해시맵으로 관리하여 중복 복사를 방지한다. 방향성은 없고 간선 그래프를 순회하는 DFS 비슷한 방식으로 연결 요소를 복제한다.

📊 시간/공간 복잡도 분석

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

피드백: 깊은 복사 방식으로 그래프를 순회하며 각 노드를 새 노드로 생성하고 이웃 관계를 재구성한다. 방문 맵을 사용해 중복 방문을 피한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
# 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']:

visited = {}

def deep_copy(node):
if node is None:
return None

cur = Node(node.val)
visited[node.val] = cur

cur.val = node.val
for neighbor in node.neighbors:
if neighbor.val in visited:
cur.neighbors.append(visited[neighbor.val])
else:
cur.neighbors.append(deep_copy(neighbor))

return cur

return deep_copy(node)
25 changes: 25 additions & 0 deletions longest-repeating-character-replacement/parkhojeong.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/parkhojeong.py
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        freq = [0] * 26
        max_len = 0

        def idx(ch):
            return ord(ch) - ord('A')

        left = 0
        for i in range(len(s)):
            freq[idx(s[i])] += 1
            window_size = i - left + 1
            size = window_size - max(freq)

            while size > k:
                freq[idx(s[left])] -= 1

                left += 1
                window_size -= 1
                size = window_size - max(freq)

            max_len = max(max_len, window_size)

        return max_len
  • 패턴: Two Pointers, Sliding Window, Greedy
  • 설명: 한 창의 양쪽 포인터를 움직이며 현 창의 길이를 최대화하는 구간 문자열 문제로, 창 크기 유지와 허용 횟수(k) 내에서 문자 교체를 최적화하는 슬라이딩 윈도우 및 그리디 성격의 접근입니다.

📊 시간/공간 복잡도 분석

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

피드백: 윈도우의 크기를 늘리며 현재 윈도우의 빈도 중 최다빈도(freq 최대)값을 이용해 필요한 변경 수를 계산한다. 필요 시 왼쪽 경계를 이동한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
freq = [0] * 26
max_len = 0

def idx(ch):
return ord(ch) - ord('A')

left = 0
for i in range(len(s)):
freq[idx(s[i])] += 1
window_size = i - left + 1
size = window_size - max(freq)

while size > k:
freq[idx(s[left])] -= 1

left += 1
window_size -= 1
size = window_size - max(freq)

max_len = max(max_len, window_size)

return max_len

15 changes: 15 additions & 0 deletions palindromic-substrings/parkhojeong.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/parkhojeong.py
class Solution:
    def countSubstrings(self, s: str) -> int:
        s_len = len(s)
        success = set([(i, i + 1) for i in range(s_len)])

        for r in range(s_len):
            for l in range(0, r):
                if r - l == 1 and s[l] == s[r]:
                    success.add((l, r + 1))
                    continue

                if (l + 1, r) in success and s[l] == s[r]:
                    success.add((l, r + 1))

        return len(success)
  • 패턴: Dynamic Programming, Two Pointers
  • 설명: 부분 문자열 팰린드롬 여부를 확장해가며 가능한 구간을 기록하는 방식으로, 왼쪽과 오른쪽 포인터의 이동 및 확장을 통해 모든 부분 문자열을 탐색합니다. 연속된 문자 매칭과 이전 구간의 상태를 이용해 새로운 구간을 만들어 내는 점이 핵심입니다.

📊 시간/공간 복잡도 분석

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

피드백: 각 부분 문자열을 검사하는 대신 현재 로직은 비효율적으로 보이며, 중심 확장 또는 DP를 이용하면 시간복잡도를 개선할 수 있다.

개선 제안: 고려해볼 만한 대안: 중심 확장법으로 각 인덱스를 중심으로 좌우 확장하며 모든 팰린드롬의 개수를 세는 것으로 O(n^2) 시간, O(1) 공간으로 구현 가능.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution:
def countSubstrings(self, s: str) -> int:
s_len = len(s)
success = set([(i, i + 1) for i in range(s_len)])

for r in range(s_len):
for l in range(0, r):
if r - l == 1 and s[l] == s[r]:
success.add((l, r + 1))
continue

if (l + 1, r) in success and s[l] == s[r]:
success.add((l, r + 1))

return len(success)
9 changes: 9 additions & 0 deletions reverse-bits/parkhojeong.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/parkhojeong.py
class Solution:
    def reverseBits(self, n: int) -> int:
        m = 0
        for i in range(32):
            remainder = n % 2
            n = n // 2
            m += pow(2, 31 - i) * remainder

        return m
  • 패턴: Bit Manipulation
  • 설명: 주어진 코드는 정수를 비트 단위로 뒤집는 연산을 수행한다. 비트를 한 비트씩 추출하고 반대쪽으로 재배치하는 방식으로, 비트 조작 및 시프트/나눗셈을 이용한 변환이 핵심이다.

📊 시간/공간 복잡도 분석

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

피드백: 비트를 하나씩 뒤집으며 결과에 누적하는 직접 구현이다. 비트 연산으로도 최적화 가능하지만 현재 방식은 직관적이다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Solution:
def reverseBits(self, n: int) -> int:
m = 0
for i in range(32):
remainder = n % 2
n = n // 2
m += pow(2, 31 - i) * remainder

return m
Loading