Linked List Cycle II
LeetCode 142 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Meet, reset one to head, step together → cycle start.
ನಾನು Linked List Cycle II (LeetCode 142) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Fast & Slow Pointers ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.
Approach
- 1
Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle).
- 2
Phase 2: fast = head.
- 3
Advance both by one until they meet; return that node.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Floyd two-phasePythonO(n) time · O(1) space
class Solution:
def detectCycle(self, head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if fast is None or fast.next is None:
return None
fast = head
while slow != fast:
slow = slow.next
fast = fast.next
return slowLinked List Cycle II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Linked List Cycle II ಹಿಂದಿನ intuition ಏನು?
After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.
Linked List Cycle II (LeetCode 142) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle). 2. Phase 2: fast = head. 3. Advance both by one until they meet; return that node.
Linked List Cycle II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Floyd two-phase.)
Linked List Cycle II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Return null when phase 1 ends without meeting.