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
21 changes: 21 additions & 0 deletions longest-repeating-character-replacement/njngwn.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/njngwn.py
class Solution:
    # Time Complexity: O(n), n: len(s)
    # Space Complexity: O(1)
    def characterReplacement(self, s: str, k: int) -> int:
        count = [0] * 26
        max_len, max_cnt = 0, 0
        left = 0

        for right in range(len(s)):  # window expands
            ch = ord(s[right]) - ord('A')
            count[ch] += 1
            max_cnt = max(max_cnt, count[ch])

            # len(substring) - len(most frequent character) > k => window needs to schrink
            if (right - left + 1) - max_cnt > k:
                count[ord(s[left]) - ord('A')] -= 1
                left += 1

            max_len = max(max_len, right - left + 1)

        return max_len
  • 패턴: Sliding Window, Greedy
  • 설명: 고정된 윈도우 크기로 문자 빈도수를 유지하며, 윈도우를 확장/축소하는 방식으로 부분 문자열의 조건을 만족시키는지 확인한다. 최대로 길이를 갱신하는 방식은 부분 문자열의 길이를 최대화하는 그리디적 아이디어와 연계된다.

📊 시간/공간 복잡도 분석

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

피드백: 알파벳 26개 카운트 배열을 사용하여 현재 윈도우의 각 문자 출현을 추적한다. 최대 빈도수를 갱신하며 윈도우를 확장/축소한다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
# Time Complexity: O(n), n: len(s)
# Space Complexity: O(1)
def characterReplacement(self, s: str, k: int) -> int:
count = [0] * 26
max_len, max_cnt = 0, 0
left = 0

for right in range(len(s)): # window expands
ch = ord(s[right]) - ord('A')
count[ch] += 1
max_cnt = max(max_cnt, count[ch])

# len(substring) - len(most frequent character) > k => window needs to schrink
if (right - left + 1) - max_cnt > k:
count[ord(s[left]) - ord('A')] -= 1
left += 1
Comment on lines +15 to +17

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.

좋은 접근인 거 같습니다


max_len = max(max_len, right - left + 1)

return max_len
22 changes: 22 additions & 0 deletions palindromic-substrings/njngwn.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/njngwn.py
class Solution:
    # Time Complexity: O(n^2), n: len(s)
    # Space Complexity: O(1)
    def countSubstrings(self, s: str) -> int:
        cnt = 0

        for i in range(len(s)):
            # odd number
            start, end = i, i
            while start >= 0 and end < len(s) and s[start] == s[end]:
                start -= 1
                end += 1
                cnt += 1

            # even number
            start, end = i, i + 1
            while start >= 0 and end < len(s) and s[start] == s[end]:
                start -= 1
                end += 1
                cnt += 1

        return cnt
  • 패턴: Two Pointers, Monotonic Stack, Dynamic Programming
  • 설명: 가장자어 확장으로 팰린드롬을 확장해가며 더해가는 방식으로 두 개의 포인터(start, end)를 가운데에서 양쪽으로 이동시키는 패턴이 핵심입니다. 이를 통해 모든 중심에서 팰린드롬을 탐색하는 'Two Pointers' 응용이고, 부분 문자열의 개수를 세는 데 사용됩니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
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,22 @@
class Solution:
# Time Complexity: O(n^2), n: len(s)
# Space Complexity: O(1)
def countSubstrings(self, s: str) -> int:
cnt = 0

for i in range(len(s)):
# odd number
start, end = i, i
while start >= 0 and end < len(s) and s[start] == s[end]:
start -= 1
end += 1
cnt += 1

# even number
start, end = i, i + 1
while start >= 0 and end < len(s) and s[start] == s[end]:
start -= 1
end += 1
cnt += 1
Comment on lines +10 to +20

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.

초기값만 다르고 로직은 동일해서 헬퍼함수 하나를 두면 의도가 더 명확해질 거 같네요


return cnt
15 changes: 15 additions & 0 deletions reverse-bits/njngwn.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/njngwn.py
class Solution:
    # Time Complexity: O(1)
    # Space Complexity: O(1)
    def reverseBits(self, n: int) -> int:
        stack = []
        for i in range(32):
            stack.append(n % 2)
            n //= 2

        res, multiples = 0, 1
        while stack:
            res += (stack.pop() * multiples)
            multiples *= 2

        return res
  • 패턴: Stack
  • 설명: 주어진 코드는 비트를 스택에 차례로 넣고(pop) 다시 꺼내며 순서를 뒤집어 결과를 구성한다. 비트 역순을 얻기 위해 스택 활용 패턴이 적용되므로 Stack 패턴에 해당한다.

📊 시간/공간 복잡도 분석

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

피드백: 비트를 스택에 저장한 뒤 역순으로 합치는 간단한 구현이다. 상수 크기의 고정된 루프를 사용한다.

개선 제안: 코드의 의도를 더 명확히 하기 위해 비트 연산 기반의 풀이로도 대체하면 자주 요구되는 최적화가 가능하다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution:
# Time Complexity: O(1)
# Space Complexity: O(1)
def reverseBits(self, n: int) -> int:
stack = []
for i in range(32):
stack.append(n % 2)
n //= 2
Comment on lines +5 to +8

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.

스택 없이 비트 연산으로 구현해보셔도 좋을 거 같습니다.


res, multiples = 0, 1
while stack:
res += (stack.pop() * multiples)
multiples *= 2

return res
Loading