Linked List Cycle

EasyLinked lists

You get the head of a singly linked list. Return true if following the next pointers from the head ever brings you back to a node you have already passed, and false if the list ends in null.

On this page a list is written as an array of its values, from head to tail, plus pos: the index of the node the tail’s next points back to, or -1 if the tail points to null. pos only describes the input. It is not passed to your function, which gets the head alone.

Examples

Example 1
Input:  head = [6, 2, 9, 4], pos = 1
Output: true

The tail, 4, points back to the node at index 1, the 2.

Example 2
Input:  head = [6, 2, 9, 4], pos = -1
Output: false

The same values, but the tail points to null, so the walk ends.

Constraints

  • The list has 0 to 10⁴ nodes.
  • -10⁵ ≤ node.val ≤ 10⁵
  • pos is -1 or a valid index in the list.

Stuck?

Hint 1

Values can repeat, so remembering values is not enough. Remember nodes, or find a way that needs no memory at all.

Hint 2

Move one pointer one step at a time and another two steps. If there is a loop, the fast one laps the slow one and they meet; if not, the fast one reaches null.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur