AlgoLounge

Linked List Cycle Detection

easy

Leetcode 141. Linked List Cycle

Given the beginning of a linked list head, return true if there is a cycle in the linked list. Otherwise, return false.

There is a cycle in a linked list if at least one node in the list can be visited again by following the next pointer.

Internally, index determines the index of the beginning of the cycle, if it exists. The tail node of the list will set its next pointer to the index-th node. If index = -1, then the tail node points to null and no cycle exists.

Note: index is not given to you as a parameter.

Examples

Example 1

Input:  head = [3,2,0,-4], pos = 1
Output: true

There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed)

Example 2

Input:  head = [1,2], pos = 0
Output: true

There is a cycle in the linked list, where the tail connects to the 0th node

Example 3

Input:  head = [1], pos = -1
Output: false

There is no cycle in the linked list

Constraints

  • 1 <= Length of the list <= 1000
  • -1000 <= Node.val <= 1000
  • index is -1 or a valid index in the linked list

How the tests work: pos is the index the tail links back to (-1: no cycle). It is only used to build the list — your function receives just head.

TypeScript
Loading editor…
List of test cases (10)
Case 1
head = [3,2,0,-4]
pos = 1
Case 2
head = [1,2]
pos = 0
Case 3
head = [1]
pos = -1
Case 4
head = [1,2,3,4,5]
pos = -1
Case 5
head = [1,2,3,4,5]
pos = 2
Case 6
head = []
pos = -1
Case 7
head = [7,8,9,10]
pos = 3
Case 8
head = [5,6]
pos = -1
Case 9
head = [10,20,30]
pos = 0
Case 10
head = [100,200,300,400,500,600]
pos = 4