1. Visited Node Reference Hash Set
Traverse the list once while recording each node's pointer/object identity in a Hash Set; a repeated pointer proves a cycle exists.
Visits each node at most once with O(1) average hash-set lookups.
Stores up to N node pointers in the hash set.
How It Works
Recording Previously Seen Memory Addresses
The most direct test for revisiting a node is storing every visited node reference (NOT its integer .val) inside a visited set:
- Start at
curr = head. - While
curr != null:
- If
curralready exists invisited, returntrue. - Add
currtovisitedand advancecurr = curr.next.
- Reaching
nullconfirms there is no cycle (return false).
Step-by-Step Dry Run
Insert distinct node references for 3, 2, 0, and -4 sequentially into visited.
visited size = 4- +Minimal mental overhead
- +Naturally exposes the exact entry node of the cycle on first revisit
- -Allocates O(n) extra memory
- -Hash collisions/overhead slower than raw two-pointer traversal
Reference Implementation
Complete implementation for Visited Node Reference Hash Set in Python, JavaScript, Java, C++, and C.
def has_cycle_set(head) -> bool:visited = set()curr = headwhile curr:if curr in visited:return Truevisited.add(curr)curr = curr.nextreturn False
function hasCycleSet(head) {
const visited = new Set();
let curr = head;
while (curr !== null) {
if (visited.has(curr)) return true;
visited.add(curr);
curr = curr.next;
}
return false;
}import java.util.HashSet;
import java.util.Set;
public class Solution {
static class ListNode { int val; ListNode next; }
public static boolean hasCycleSet(ListNode head) {
Set<ListNode> visited = new HashSet<>();
ListNode curr = head;
while (curr != null) {
if (!visited.add(curr)) return true;
curr = curr.next;
}
return false;
}
}#include <unordered_set>
struct ListNode { int val; ListNode* next; };
bool hasCycleSet(ListNode* head) {
std::unordered_set<ListNode*> visited;
for (ListNode* curr = head; curr != nullptr; curr = curr->next) {
if (visited.count(curr)) return true;
visited.insert(curr);
}
return false;
}#include <stdbool.h>
#include <stdlib.h>
struct ListNode { int val; struct ListNode* next; };
bool hasCycleLinearCheck(struct ListNode* head) {
// Without a hash table in C, store visited pointers in a small lookup array
// (prefer Floyd's O(1) Tortoise & Hare for O(n) speed).
struct ListNode* seen[10005];
int count = 0;
for (struct ListNode* cur = head; cur != NULL; cur = cur->next) {
for (int i = 0; i < count; i++) {
if (seen[i] == cur) return true;
}
seen[count++] = cur;
}
return false;
}