InterviewPrepKit

Home / Coding / Linked List

Linked List Cycle

easy Original ↗
Solving tips
  • Use Floyd's fast/slow pointers (1 step vs 2 steps): in a cycle the gap shrinks by 1 each step so they must meet; without a cycle fast falls off the end.
  • The follow-up wants O(1) memory, which rules out the visited-set approach; the two-pointer walk is O(n) time, O(1) space.
  • Loop while 'fast and fast.next' and compare with 'is' (identity), not '==' on values, since values can legitimately repeat.
  • Advance the pointers BEFORE checking slow is fast; they both start at head, so a pre-move check falsely returns True on every non-empty list.

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.