Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get head, the first node of a linked list. Normally the last node's next is null. But here the last node might instead point back to some earlier node, which creates a cycle (a loop). Return true if there's a cycle and false otherwise.
LeetCode describes the input with a number pos: the index the tail links back to, or -1 for no cycle. Your function never sees pos. It only gets head. The list has up to 10,000 nodes.
Example: values 3 → 2 → 0 → -4 where -4 links back to 2 (pos = 1) → true.
Start with brute force
Walk the list and put every node you visit into a hash set. Before adding a node, check if it's already there. If it is, you've come back round: cycle. If you reach null, no cycle.
Store the nodes themselves (their identity), not their values. Two different nodes can both hold the value 1.
This is O(n) time and O(n) space. It's a fine first answer. The follow-up is always: "Can you do it with O(1) memory?"
Building the intuition
Without extra memory you can't remember where you've been. So you need some other way to notice "I'm going round in circles."
Think of two friends running on a track. If the track is a straight road with an end, the faster friend just reaches the end first. But if the track is a loop, the faster friend keeps going round and eventually comes up behind the slower friend and passes them. That moment of being in the same place is your proof of a loop.
Turn that into pointers. slow moves one node per step. fast moves two.
- No cycle:
fastreachesnull(or a node whosenextisnull) first. Answerfalse. - Cycle: both pointers eventually enter the loop and go round forever. Once they're both in it, measure how far
fastis behindslow, going forward round the loop. Each stepslowadds 1 to that distance andfasttakes away 2, so the gap shrinks by exactly 1 per step. A gap that shrinks by 1 can't jump over 0. They will land on the same node within one lap.
The optimal approach
- Start
slowandfastathead. - While
fastandfast.nextboth exist:slow = slow.nextfast = fast.next.next- If
slowandfastare the same node, returntrue.
- If the loop exits,
fasthit the end. Returnfalse.
The subtle detail is the loop condition. fast jumps two nodes, so before the jump you need fast to exist and fast.next to exist. Checking only fast crashes on fast.next.next when the list has an even length. You never need to check slow: it's always behind fast, so if fast is safe, slow is too.
Also check for a meeting after moving, not before. At the start both are on head, so checking first would always say true.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head # slow moves 1 step per turn, fast moves 2
# fast reaches the end first if there is one, so only fast needs checking
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # same node (not just same value): fast lapped slow inside a loop
return True
return False # fast hit the end, so there is no loopclass Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head; // moves 1 step per turn
ListNode* fast = head; // moves 2 steps per turn
// fast reaches the end first if there is one, so only fast needs checking
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) { // same node (not just same value): fast lapped slow inside a loop
return true;
}
}
return false; // fast hit the end, so there is no loop
}
};public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head; // moves 1 step per turn
ListNode fast = head; // moves 2 steps per turn
// fast reaches the end first if there is one, so only fast needs checking
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // same node (not just same value): fast lapped slow inside a loop
return true;
}
}
return false; // fast hit the end, so there is no loop
}
}/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
let slow = head; // moves 1 step per turn
let fast = head; // moves 2 steps per turn
// fast reaches the end first if there is one, so only fast needs checking
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) { // same node (not just same value): fast lapped slow inside a loop
return true;
}
}
return false; // fast hit the end, so there is no loop
};Dry run
Values 3 → 2 → 0 → -4, and -4 links back to 2. Call the nodes A(3), B(2), C(0), D(-4). The list state never changes here; we only move pointers.
| Step | slow | fast | Same node? |
|---|---|---|---|
| start | A (3) | A (3) | not checked |
| 1 | B (2) | C (0) | no |
| 2 | C (0) | B (2): C → D → B | no |
| 3 | D (-4) | D (-4): B → C → D | yes → true |
Now the no-cycle case 1 → 2 → 3: after step 1, slow is on 2 and fast is on 3. fast.next is null, so the loop stops and we return false.
Complexity
- Time: O(n). With no cycle,
fastreaches the end in about n/2 steps. With a cycle,slowgets into the loop within n steps, and then they meet within one more lap, which is at most n steps. - Space: O(1). Two pointers.
Edge cases and traps
- Empty list or one node with no loop.
fastorfast.nextisnullstraight away, so returnfalse. - One node pointing at itself. Step 1:
slowandfastboth land on that node. Returntrue. - Comparing values instead of nodes.
slow.val == fast.valgivestruefor1 → 1with no cycle. Compare the references (isin Python,==on pointers or objects elsewhere). - Checking only
fast. Crashes onfast.next.nextwhenfast.nextisnull. - Checking for a meeting before moving. Both start on
head, so you'd always returntrue.
Say it in the interview
"A hash set of visited nodes works but costs O(n) space. Instead I'll use Floyd's fast and slow pointers. Slow moves one step, fast moves two. If there's no cycle, fast reaches null. If there is one, both end up in the loop, and the gap between them shrinks by one node each step, so they have to meet. I compare node references, not values. That's O(n) time and O(1) space."
Follow-ups interviewers ask
- "Where does the cycle start?" That's Linked List Cycle II. After they meet, move one pointer back to
headand step both one node at a time. They meet again exactly at the start of the loop. - "How long is the cycle?" After they meet, keep
faststill and walkslowround until it comes back, counting steps. - "Why speed 2? Why not 3?" Speed 2 makes the gap shrink by exactly 1, so they can't skip past each other. With other speeds they still meet eventually, but the argument is messier and you gain nothing.
Practise the same idea
This is Day 45 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free