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
41 changes: 41 additions & 0 deletions linked-list-cycle/socow.py
Copy link
Contributor

Choose a reason for hiding this comment

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

토끼와 거북이 알고리즘을 잘 적용하신 것 같습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
📚 141. Linked List Cycle

📌 문제 요약
- 연결 리스트에 사이클(순환)이 있는지 확인하기
- 있으면 True, 없으면 False

🎯 핵심 알고리즘
- 패턴: 플로이드 순환 탐지 (토끼와 거북이)
- 시간복잡도: O(n)
- 공간복잡도: O(1)

💡 핵심 아이디어
1. slow는 한 칸씩, fast는 두 칸씩 이동
2. 사이클이 있으면 → 둘이 언젠가 만남!
3. 사이클이 없으면 → fast가 끝에 도달 (None)
"""

from typing import Optional


class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head

while fast and fast.next:
slow = slow.next # 거북이: 한 칸
fast = fast.next.next # 토끼: 두 칸

if slow == fast: # 만났다!
return True

return False # fast가 끝에 도달 = 사이클 없음

17 changes: 0 additions & 17 deletions longest-substring-without-repeating-characters/socow.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,4 @@ def lengthOfLongestSubstring(self, s: str) -> int:
return max_len


# Set을 사용한 방식 (더 직관적)
class SolutionWithSet:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
left = 0
max_len = 0

for right in range(len(s)):
# 중복이 사라질 때까지 left 이동
while s[right] in char_set:
char_set.remove(s[left])
left += 1

char_set.add(s[right])
max_len = max(max_len, right - left + 1)

return max_len