 All Problems
Linked List Cycle
easy
linked list
two pointers
hash table
amazon
microsoft
apple

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.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input:
3 2 0 -4
1
Output: true

(pos=1 means tail connects back to node at index 1)

Example 2:

Input:
1 2
0
Output: true

Example 3:

Input:
1
-1
Output: false

Constraints:

  • The number of the nodes in the list is in the range [0, 10⁴]
  • -10⁵ ≤ Node.val ≤ 10⁵
  • pos is -1 or a valid index in the linked-list

Input format: First line: space-separated node values. Second line: pos (-1 means no cycle; non-negative integer means the tail's next points to node at that index).

Output format: true or false.

Run to check your code against the sample cases, or submit to run every case