Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Linked List

Linked List Cycle

easy

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Write a function that takes in a parameter head of type ListNode that is a reference to the head of a linked list. The function should return True if the linked list contains a cycle, and False otherwise, without modifying the linked list in any way.

# Definition of a ListNode
class ListNode:
  def __init__(self, value=0, next=None):
    self.value = value
    self.next = next

Example 1:

54320head

Output: true, there is a cycle between node 0 and node 3.

Example 2:

54320head

Output: false, there is no cycle in the linked list.

We recommend taking some time to solve the problem on your own before reading the solutions below.

Solutions

1. Keep Track of Visited Nodes

One approach to this problem is to keep a set of visited nodes while iterating through the linked list. At each node, we check if the node exists in the set. If it does, then the linked list contains a cycle. If it doesn't, we add the node to the set and move to the next node. If we reach the end of the linked list without encountering a node in the dictionary, then the linked list does not contain a cycle.
Solution
Python
Language
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
visited_nodes = set()
current_node = head
while current_node is not None:
if current_node in visited_nodes:
return True # Cycle detected
visited_nodes.add(current_node)
current_node = current_node.next
return False
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the number of nodes in the linked list. In the worst case scenario, the algorithm visits each node once.

Space Complexity: O(n) where n is the number of nodes in the linked list. The space complexity is due to the set storing visited nodes.

2. Optimal Solution: Fast and Slow Pointers

The approach above requires O(n) space to store each visited node in the set. A more optimal solution solves this problem without using additional space (i.e. constant, O(1) space) by using fast and slow pointers.
This approach starts by initializing two pointers, fast and slow at the head of the list. It then iterates over the linked list, and in each iteration, the slow pointer advances by one node, while the fast pointer advances by two nodes.

Detecting a Cycle

If the linked list contains a cycle, the fast pointer will eventually overlap the slow pointer, and both pointers will point to the same node.
Visualization
54320slowfast

initialize pointers

0 / 4

When the list contains a cycle, fast and slow eventually meet at the same node.

No Cycle

When there is no cycle, the fast pointer reaches the tail of the linked list, where fast.next = None (step 3 in the animation below). This is enough to determine the linked list does not contain a cycle.
Visualization
54320slowfast

initialize pointers

0 / 3

If there is no cycle, eventually `fast.next = None`
When there is no cycle and the linked list has an even number of nodes, eventually fast = None (step 2 in the animation below).
Visualization
5430slowfast

initialize pointers

0 / 3

Even # of nodes and no cycle, eventually `fast.next = None`
Putting it all together, our algorithm involves the following steps:
  • Initialize fast and slow pointers at the head of the linked list.
  • Iterate over the linked list. Each iteration advances slow by one node and fast by two nodes.
  • If the fast pointer reaches the end of the linked list (either fast.next = None or fast = None), then the linked list does not contain a cycle.
  • If the fast and slow pointers meet at the same node (fast == slow), then the linked list contains a cycle.

Code

To construct the linked list that is used in the animation below, provide a list of integers nodes and an integer tail. Each integer in nodes is used as the value of a node in the linked list, and the order of the integers in the list will be the order of the nodes in the linked list.
The tail integer is the index of the node that the last node in the linked list points to form a cycle. If there is no cycle, set tail = -1.
Visualization
Python
Language
Try these examples:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
54320

linked list cycle

0 / 5

Edge Cases

Empty List

When the linked list is empty, fast = None to start, the while loop never runs and the function returns False.
Visualization
Python
Language
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False

linked list cycle

0 / 2

`nodes = []`, `tail = -1`

Single Node (No Cycle)

When the linked list contains a single node without a cycle, fast.next = None to start and the function returns False without running the while loop.
Visualization
Python
Language
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
1

linked list cycle

0 / 2

`nodes = [1]`, `tail = -1`

Single Node (with Cycle)

When the linked list contains a single node with a cycle, slow.next and fast.next.next point to the same single node, and the function returns True during the first iteration of the while loop.
Visualization
Python
Language
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
1

linked list cycle

0 / 3

`nodes = [1]`, `tail = 0`

Worst Case Scenario

In the worst case scenario, the fast pointer traverses the entire list twice before meeting the slow pointer.
Visualization
Python
Language
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
5432

linked list cycle

0 / 6

`nodes = [5, 4, 3, 2]`, `tail = 0`
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the number of nodes in the linked list. In the worst case scenario, the fast pointer traverses the linked list twice, and the slow pointer traverses the linked list once, regardless of the number of nodes in the linked list.

Space Complexity: O(1) We only use two pointers to do our traversal, which does not change with the number of nodes in the linked list.

Mark as read

Next: Palindrome Linked List

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Solutions

1. Keep Track of Visited Nodes

2. Optimal Solution: Fast and Slow Pointers

Code

Edge Cases

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress