Linked List Cycle
LeetCode 141 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Floyd: fast meets slow ⇔ cycle.
ನಾನು Linked List Cycle (LeetCode 141) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Fast & Slow Pointers ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.
Approach
- 1
slow and fast start at head.
- 2
Advance slow by 1 and fast by 2.
- 3
Equal → cycle; fast hits None → no cycle.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Floyd's cycle detectionPythonO(n) time · O(1) space
# 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:
slow = head
fast = head
while fast and fast.next!=None:
slow = slow.next
fast = fast.next.next
if slow==fast:
return True
return FalseLinked List Cycle — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Linked List Cycle ಹಿಂದಿನ intuition ಏನು?
Send a slow pointer one step and a fast pointer two steps. If there is a loop, the fast one eventually laps the slow one and they meet; if not, the fast pointer reaches the end.
Linked List Cycle (LeetCode 141) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. slow and fast start at head. 2. Advance slow by 1 and fast by 2. 3. Equal → cycle; fast hits None → no cycle.
Linked List Cycle ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Floyd's cycle detection.)
Linked List Cycle ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Compare nodes (identity), not values.