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
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
33 changes: 33 additions & 0 deletions longest-substring-without-repeating-characters/jamiebase.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Sliding Window
  • 설명: 이 코드는 슬라이딩 윈도우 기법을 사용하여 문자열 내에서 중복되지 않는 가장 긴 구간을 찾는다. 왼쪽과 오른쪽 포인터를 이동시키며 조건에 맞게 윈도우를 확장하거나 축소한다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
# Approach
슬라이딩 윈도우를 사용한다.
right 포인터를 하나씩 이동시키면서 문자열을 확장하고,
이미 등장한 문자를 만나면 해당 문자의 마지막 위치를 기준으로 left 포인터를 이동시켜 중복이 없는 구간을 유지한다.
각 단계에서 현재 윈도우의 길이를 계산하여 최대값을 갱신한다.

# Complexity
문자열 길이를 N이라고 할 때, 문자 종류 수를 K라고 할 때
- Time complexity: O(N)
- Space complexity: O(K)
"""


class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last_seen = {} # 문자 -> 마지막으로 등장한 인덱스
left = 0 # 현재 윈도우의 시작 위치
answer = 0 # 최대 길이 저장

for right, ch in enumerate(s):
# 현재 문자가 이전에 등장했고,
# 그 위치가 현재 윈도우 안에 있다면 left 이동
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1

# 현재 문자의 마지막 위치 갱신
last_seen[ch] = right

# 현재 윈도우 길이 계산 및 최대값 갱신
answer = max(answer, right - left + 1)

return answer
File renamed without changes.
File renamed without changes.
File renamed without changes.
45 changes: 45 additions & 0 deletions number-of-islands/jamiebase.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: DFS
  • 설명: 이 코드는 깊이 우선 탐색(DFS)을 이용하여 연결된 육지를 찾고 방문 표시를 통해 섬의 개수를 셉니다. 재귀 호출로 인접한 노드를 탐색하는 방식이 핵심입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
# Approach
Grid의 원소에 일일이 dfs를 수행하되 값이 "1"(=육지)인 경우만 탐색을 수행합니다.
이때 방문한 노드는 값을 "-1"로 변경하여 방문 체크합니다.

# Complexity
Grid의 rows = M, cols = N이라고 할 때,
- Time complexity: O(M*N)
- Space complexity: visited set 최대 O(M*N)
"""


class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
answer = 0
direction = [(0, 1), (0, -1), (1, 0), (-1, 0)]
row = len(grid)
col = len(grid[0])

def can_go(x, y, row, col):
if x < 0 or y < 0 or x >= row or y >= col:
return False
if grid[x][y] == "0":
return False
return True

def dfs(x, y, row, col):
for dx, dy in direction:
nx, ny = x + dx, y + dy
if not can_go(nx, ny, row, col):
continue
if grid[nx][ny] == "-1": # 방문 확인
continue
grid[nx][ny] = "-1" # 방문 처리
dfs(nx, ny, row, col)

for x, row_list in enumerate(grid):
for y, value in enumerate(row_list):
if value != "1":
continue
grid[x][y] = "-1" # 방문 확인
dfs(x, y, row, col)
answer += 1

return answer
22 changes: 22 additions & 0 deletions reverse-linked-list/jamiebase.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Fast & Slow Pointers
  • 설명: 이 코드는 포인터를 이용해 리스트를 역순으로 뒤집으며, prev와 cur 포인터를 이동시키는 방식으로 진행됩니다. 빠른 또는 느린 포인터 개념보다는 포인터 이동과 방향 전환이 핵심입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
# Approach
이전 노드, 현재 노드, 다음 노드를 저장한 뒤, 현재 노드가 이전 노드를 가리키도록 방향을 바꾸고,
이전 노드와 현재 노드 포인터를 이동시킵니다.

# Complexity
List의 길이를 N이라고 할 떄
- Time complexity: O(N)
- Space complexity: O(1)
"""


class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
cur = head
while cur:
nxt = cur.next # 1. 다음 노드 저장
cur.next = prev # 2. 방향 뒤집기
prev = cur # 3. prev 이동
cur = nxt # 4. cur 이동
return prev
34 changes: 34 additions & 0 deletions set-matrix-zeroes/jamiebase.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Hash Map / Hash Set
  • 설명: 이 코드는 0이 있는 행과 열을 기록하기 위해 집합을 사용하여 빠른 검색을 수행합니다. 이를 통해 행과 열을 효율적으로 추적하고 수정하는 방식입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
# Approach
matrix를 순회하며 값이 0인 행과 열의 번호를 기록합니다.
기록한 것을 토대로 다시 matrix를 순회하며 0으로 채웁니다.

# Complexity
matrix의 행 크기를 M, 열 크기를 N이라고 할 때
- Time complexity: O(MN)
- Space complexity: O(M+N)
"""


class Solution:
def setZeroes(self, matrix: list[list[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""

rows, cols = len(matrix), len(matrix[0])
zero_rows = set()
zero_cols = set()
for x, row in enumerate(matrix):
for y, value in enumerate(row):
if value == 0:
zero_rows.add(x)
zero_cols.add(y)

for x in zero_rows:
for i in range(cols):
matrix[x][i] = 0

for y in zero_cols:
for i in range(rows):
matrix[i][y] = 0
File renamed without changes.
File renamed without changes.
16 changes: 16 additions & 0 deletions unique-paths/jamiebase.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.

🏷️ 알고리즘 패턴 분석

  • 패턴: Combinatorics
  • 설명: 이 코드는 조합 수학을 이용하여 경로의 수를 계산하므로 조합(Combinatorics) 패턴에 속합니다. 이동 경로의 선택을 수학적 조합으로 해결하는 방식입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
# Approach
(0,0) -> (m-1, n-1)로 가기 위해서는 아래로는 m-1회, 우측으로 n-1회 이동해야 합니다.
도합 m+n-2회 이동해야 합니다. 그 이동 경로 중에서 방향 전환(우측 이동 혹은 아래쪽 이동)을 하는 경우의 수를 계산하여 unique path를 구합니다.

# Complexity
- Time complexity: math.comb는 거의 상수 시간으로 취급하므로 O(1)
- Space complexity: O(1)
"""

import math


class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return math.comb(m + n - 2, m - 1)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading