Skip to content

Detect a Cycle

EasyLinked List
Decode it first. Clues, constraints, pattern and plan before any code.

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.

3 -> 2 -> 0 -> -4
     ^          |
     +----------+        →  True   (tail links back to the 2)
 
1 -> 2 -> 3 -> (end)     →  False
(empty)                  →  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