InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Linked List Cycle

easy Original ↗ 00:00

Problem

You are given the head of a singly linked list. Determine whether the list contains a cycle — that is, whether some node’s next pointer points back to an earlier node in the list, so that walking the list would loop forever instead of reaching None.

Return True if a cycle exists, False otherwise.

(LeetCode’s test harness describes the cycle with an index pos, but your function only receives headpos is not a parameter.)

Examples

  • Input: 3 -> 2 -> 0 -> -4, where -4.next points back to node 2 → Output: True Walking the list revisits node 2 forever.
  • Input: 1 -> 2, where 2.next points back to node 1 → Output: True The tail loops back to the head.
  • Input: 1 -> None → Output: False The walk terminates at None, so there is no cycle.

Constraints

  • Number of nodes is in [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • Follow-up: solve it with O(1) memory.

Think about it first

Hint 1 If there is no cycle, a walk from the head reaches None. If there is a cycle, the walk never ends. How could you tell "never ends" apart from "hasn't ended yet"?
Hint 2 A cycle means you visit some node twice. What data structure detects "seen before" in O(1) per check?
Hint 3 Send two runners down the list, one moving 1 step at a time and one moving 2. If the list loops, the fast runner eventually laps the slow one and they land on the same node — no extra memory needed.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug