FrontendInterviews.dev

Loading problem…

297. Linked List Cycle

Easyβ€’
Acceptance: 84.62%
β€’
πŸ”“3/3 Pro unlocks today

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.

Return true if there is a cycle in the linked list. Otherwise, return false.

Detect whether a linked list contains a cycle using Floyd's Tortoise and Hare algorithm β€” a two-pointer technique where one pointer moves twice as fast as the other.

Requirements

1. Basic Functionality

  • Return true if the list has a cycle, false otherwise
  • Must use O(1) extra space (no hash set)
  • Handle empty lists and single nodes

Example Usage

// List: 3 β†’ 2 β†’ 0 β†’ -4 β†’ (back to 2)  β†’  true
// List: 1 β†’ 2 β†’ null                    β†’  false

Real-World Context

  • Deadlock detection: Finding circular waits in operating systems
  • Infinite loop detection: Detecting cycles in state machines or workflows
  • Garbage collection: Identifying circular references in memory management

Constraints

  • The number of nodes in the list is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5