Start learning free

LESSON 432 OF 675 · LINKED LISTS

Linked List Cycle

Practice O(n)

You get the head of a linked list. Return true if the list has a loop, and false if it doesn't.

In a normal list, the last node's next is null. In a list with a loop, the last node points back to an earlier node, or to itself. Then following next never ends.

The examples show the loop with pos. It is the index of the node the last node points back to. Indexes start at 0, and -1 means no loop.

Your function never sees pos. The tests build the loop and pass you only head.

 

Example 1:

Input: head = [6,1,9,4], pos = 2
Output: true
Explanation: The last node (4) points back to index 2, the 9.
So the walk goes 6 -> 1 -> 9 -> 4 -> 9 -> 4 -> ... forever.

Example 2:

Input: head = [5,8,2], pos = -1
Output: false
Explanation: The last node (2) points to null.
So the walk stops there.

Example 3:

Input: head = [7], pos = 0
Output: true
Explanation: The only node points to itself.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from -100,000 to 100,000.
  • pos is -1 or the index of one of the nodes.

 

Follow up: Remembering every node you have seen works. Can you do it with only a few pointers, in O(1) extra memory?

STEP 1 OF 6
    Ctrl + Enter to check