Back to Practice Dashboard
Top 150 InterviewEasy

Linked List Cycle

Learn how to solve the 'Linked List Cycle' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

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

The input is given as a list of values and an integer pos (the index where the tail connects to, -1 if no cycle). Implement a function hasCycle(head: list, pos: int) -> bool.

Constraints
  • The number of nodes in the list is in the range [0, 10000]
  • -100000 <= Node.val <= 100000
  • pos is -1 or a valid index in the linked list

Examples

Example 1
Input
[3,2,0,-4], 1
Output
True
Explanation

There is a cycle: the tail node (-4) connects back to the node at index 1 (value 2).

Example 2
Input
[1,2], 0
Output
True
Explanation

There is a cycle: the tail node (2) connects back to the node at index 0 (value 1).

Example 3
Input
[1], -1
Output
False
Explanation

There is no cycle in the list.

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor