Skip to content
Decoder

Detect a Cycle

Easy

Problem

Given the head of a linked list, return True if the list contains a cycle, meaning some node's next points back to an earlier node so following next never ends. Return False otherwise.

Example 1

Input
3
Output
2 -> 0 -> -4

Example 2

     ^          |

Example 3

Input
+----------+
Output
True
Why
tail links back to the 2

Example 4

Input
1
Output
2 -> 3 -> (end) → False

Example 5

Input
(empty)
Output
False

Can you solve it with O(1) extra memory?

The tests build each list for you (with build_list / buildList) and link the tail to make a cycle where needed.

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.