Linked List Cycle
easyNeetCode 150linked-listtwo-pointers
Problem
Given the head of a singly linked list, decide whether it contains a cycle, meaning some node's next pointer eventually revisits an earlier node. Use constant extra space.
Examples
Input: 3 -> 2 -> 0 -> -4 with tail linking back to node 2
Output: true
Following next pointers loops forever.
Input: 1 -> 2 with no loop
Output: false
The list terminates at null.
Constraints
- • 0 <= number of nodes <= 10^4
- • Solution must use O(1) extra space
Hints(tap to reveal)
- 1. A slow and a fast pointer move at different speeds.
- 2. In a cycle the fast pointer eventually laps the slow one.
Optimal approach(spoiler)
- Advance a slow pointer one step and a fast pointer two steps per iteration.
- If the fast pointer reaches null, there is no cycle.
- If the two pointers ever meet, a cycle exists.
- This is Floyd's tortoise and hare technique.
- O(n) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor