Linked List Cycle
01 · Problem
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
02 · Examples
head = [3,2,0,-4], pos = 1
true
There is a cycle in the linked list, where the tail connects back to the node at index 1 (value 2).
head = [1,2], pos = 0
true
There is a cycle in the linked list, where the tail connects back to the node at index 0 (value 1).
head = [1], pos = -1
false
There is no cycle in the linked list since pos is -1.
03 · Constraints
- 01The number of nodes in the list is in the range [0, 104].
- 02-105 <= Node.val <= 105
- 03pos is -1 or a valid index in the linked list.
04 · Optimal complexity
- Time
- O(n)
- Space
- O(1)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.