Back to Dashboard

Start of LinkedList Cycle

Medium

Problem Statement

Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.

Examples

Example 1:

  • Input: [3,2,0,-4], pos = 1
  • Output: tail connects to node index 1

Approach 1 Slow Fast Pointers:

/**
 * 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) {
        var slow = head;
        var fast = head;
        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow.equals(fast)) {
                fast = head;
                while (!slow.equals(fast)) {
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

Linked ListSlow Fast Pointers

Date

2026-02-10
View Problem Source