Detect a Loop in a Linked List

Problem Given the head of a singly linked list, determine whether it contains a cycle — i.e. whether some node's next pointer eventually points back to an earlier node.

Input / Output

  • Input: head — pointer to the first node of a singly linked list.
  • Output: boolean — true if a cycle exists.

Constraints

  • 0 <= number of nodes <= 10^4; node values must not be modified or used as markers.
  • Aim for O(1) extra space; a hash-set answer is accepted but the interviewer will push for constant space.

Example

  • 1 -> 2 -> 3 -> 4 -> 2 (tail points back to node 2) → true.
  • 1 -> 2 -> 3 -> NULL → false.
  • Tricky cases: a single node pointing to itself → true; an empty list → false.
asked …
LeaderboardSalaryAccount