Leetcode 142. Linked List Cycle II
LeetCode Problem 142: Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent the cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where the tail connects to form a cycle. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
null.null to avoid null pointer exceptions.To solve this problem, we can use Floyd’s Tortoise and Hare algorithm, which consists of two main steps:
slow) that moves one step at a time, and a fast pointer (fast) that moves two steps at a time. If there’s a cycle, the fast pointer will eventually meet the slow pointer within the cycle.// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
// Step 1: Detect if there is a cycle
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// Cycle detected
break;
}
}
// If there is no cycle
if (fast == null || fast.next == null) {
return null;
}
// Step 2: Find the entry point to the cycle
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow; // The start of the cycle
}
}
This is the most efficient solution for the problem, as it finds the cycle and its starting node using the least possible amount of time and space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?