Blind 75
23 / 75Free practice

Linked List Cycle

Easy · Linked lists

Jump to code

Determine whether repeatedly following next pointers in a singly linked list can revisit a node. Compare node identity, not values.

Examples

Example 1

head = [3,2,0,-4]
pos = 1

Output: true

Example 2

head = [1,2]
pos = 0

Output: true

Constraints

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

Function contract

Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.

head is built from the values array; pos is the zero-based index that the tail links to, or -1 for no cycle. Your function receives head, not pos.

Need a hint?

Two runners moving at different speeds eventually meet inside a cycle.

Asked in real interviews

Candidates reported versions of Linked List Cycle from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    2,
    0,
    -4
  ],
  1
]
Expected
true
Case 2
Input
[
  [
    1,
    2
  ],
  0
]
Expected
true
Case 3
Input
[
  [
    1
  ],
  -1
]
Expected
false
Case 4
Input
[
  [
    1,
    2,
    3
  ],
  -1
]
Expected
false
Case 5
Input
[
  [
    1,
    2,
    3,
    4
  ],
  2
]
Expected
true

Drafts are saved per language in this browser when storage is available.