Linked List Cycle II - Problem

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Input & Output

Example 1 — Cycle Exists
$ Input: head = [3,2,0,-4], pos = 1
Output: Node with value 2
💡 Note: The cycle begins at node with value 2 (index 1). The last node (-4) points back to the node with value 2.
Example 2 — Self Loop
$ Input: head = [1,2], pos = 0
Output: Node with value 1
💡 Note: The cycle begins at the head node (value 1). The second node points back to the first node.
Example 3 — No Cycle
$ Input: head = [1], pos = -1
Output: null
💡 Note: There is only one node and no cycle exists, so return null.

Constraints

  • The number of the nodes in the list is in the range [0, 104]
  • -105 ≤ Node.val ≤ 105
  • pos is -1 or a valid index in the linked-list

Visualization

Tap to expand
Linked List Cycle II - Floyd's Algorithm INPUT 3 idx 0 2 idx 1 (cycle start) 0 idx 2 -4 idx 3 cycle Input Parameters: head = [3, 2, 0, -4] pos = 1 (tail connects to idx 1) head ALGORITHM STEPS 1 Initialize Pointers slow = fast = head 2 Detect Cycle slow moves 1, fast moves 2 Until they meet (if cycle) 3 Find Cycle Start Reset slow to head Both move 1 step each 4 Return Meeting Point Where they meet is cycle start Pointer Positions: slow: 3-->2-->0-->-4-->2 fast: 3-->0-->2-->-4-->2 Meet at node -4 Then both meet at node 2 FINAL RESULT 2 cycle start Output: Node with value 2 [OK] Cycle detected at index 1 Complexity: Time: O(n) Space: O(1) Verified: -4.next points to 2 Cycle entry found correctly Key Insight: Floyd's Tortoise and Hare algorithm uses mathematical property: if slow travels distance X before meeting fast inside the cycle, then the distance from head to cycle start equals distance from meeting point to cycle start. This allows O(1) space detection without modifying the list. TutorialsPoint - Linked List Cycle II | Floyd's Cycle Detection (Optimal Solution)
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
180.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen