Linked List Cycle
Easy · Linked List
You are given the head of a singly linked list. Some implementations of such a list can be malformed so that a node's next pointer loops back to an earlier node instead of eventually reaching null. Determine whether the given list contains such a loop anywhere in it. Return true if a cycle exists, and false if the list terminates normally.
Examples
Input: head = [3,2,0,-4], the last node points back to index 1
Output: true
Why: Following next pointers from the last node leads back into the list, so it never reaches null and forms a loop.
Input: head = [1,2], the last node points back to index 0
Output: true
Why: The tail connects to the head, so traversal repeats forever.
Input: head = [1]
Output: false
Why: The single node's next pointer is null, so traversal ends without revisiting anything.
Constraints
0 <= number of nodes <= 10^4, -10^5 <= node value <= 10^5, the list may loop back to an earlier node in it
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Linked List Cycle. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.