Leetcode 142: Linked List Cycle II

grid47
grid47
Exploring patterns and algorithms
Oct 23, 2024 6 min read

A cycle in the linked list gently glowing, with the starting node illuminated to indicate the cycle's start.
Solution to LeetCode 142: Linked List Cycle II Problem

Given the head of a linked list, find the node where the cycle begins. If no cycle exists, return null. The list may contain a cycle, which occurs if a node can be revisited by following the ’next’ pointers continuously.
Problem
Approach
Steps
Complexity
Input: The input consists of a linked list and an index 'pos' where the tail node connects. If 'pos' is -1, there is no cycle.
Example: Input: head = [5, 3, 9, 4], pos = 2
Constraints:
• The number of nodes in the list is between 0 and 10^4.
• Node values range between -10^5 and 10^5.
• 'pos' is either -1 or a valid index within the list.
Output: The output is the node where the cycle begins, or null if no cycle is detected.
Example: Output: tail connects to node index 2
Constraints:
• The output is the node where the cycle begins, or null if no cycle exists.
Goal: The goal is to detect the node where the cycle begins in the linked list.
Steps:
• 1. Use two pointers, 'slow' and 'fast', which start at the head of the list.
• 2. Move the slow pointer one step and the fast pointer two steps at a time.
• 3. If a cycle exists, slow and fast pointers will meet at some point.
• 4. Once a cycle is detected, reset one pointer to the head and keep the other at the meeting point.
• 5. Move both pointers one step at a time until they meet again. This is the start of the cycle.
Goal: The solution should efficiently detect the cycle and identify the starting node without modifying the linked list.
Steps:
• The solution should run in linear time, O(n), and use constant space, O(1).
Assumptions:
• The linked list may contain a cycle or it may be acyclic.
• Nodes may contain integer values.
Input: Input: head = [5, 3, 9, 4], pos = 2
Explanation: In this example, the linked list has a cycle where the tail connects to the 2nd node (index 2).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus