Skip to content
Open
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
22 changes: 22 additions & 0 deletions linked-list-cycle/yuseok89.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.

🏷️ 알고리즘 패턴 분석

linked-list-cycle/yuseok89.py
# TC: O(N)
# SC: O(1)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if not head or not head.next:
            return False

        slow, fast = head, head.next
        while slow != fast:
            if not fast or not fast.next:
                return False

            slow, fast = slow.next, fast.next.next

        return True
  • 패턴: Two Pointers, Fast & Slow Pointers
  • 설명: 해당 코드는 느린 포인터와 빠른 포인터를 이용해 순환 여부를 판별하는 전형적인 Fast & Slow Pointers 패턴이다. 두 포인터의 속도 차이를 이용해 사이클 존재 여부를 O(N) 시간, O(1) 공간으로 판단한다.

📊 시간/공간 복잡도 분석

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

피드백: 빠른 포인터와 느린 포인터를 이용해 순회하므로 추가 메모리 없이 사이클 여부를 판단할 수 있다.

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

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

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.

조건문 부분에 같은지 비교를 하는것도 꽤 괜찮은 아이디어시네요!
다만 아주 개인적인 의견인데, slow와 fast를 비교하는것은 참조를 비교하는거라 is를 쓰는게 더 낫지 않을까? 하는 생각이 있었어요
좋은 코드 보고 갑니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# TC: O(N)
# SC: O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
Comment on lines +11 to +12

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

노드가 하나뿐이고 순환이 없는 입력이라면 fastNone으로 시작하므로, 반복문 안의 if not fast 가 곧바로 False를 반환해 줄텐데요. 그렇다면 여기서 not head.next까지 확인하는 것은 어떤 경우를 대응하기 위한 목적인가요?


slow, fast = head, head.next
while slow != fast:
if not fast or not fast.next:
return False

slow, fast = slow.next, fast.next.next

return True

Loading