Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Linked List Cycle

LeetCode #141Easy
Floyd's tortoise & hare

Given the head of a singly linked list, determine whether the list contains a cycle, meaning some node can be reached again by repeatedly following next pointers.

Asked atAmazonMicrosoftBloomberg
step 1 / 14
3
2
0
-4
[0][1][2][3]
Brute force · visited set
1given head
2visited = {}
3cur = head; while cur ≠ ∅:
4 if cur in visited: return true
5 add cur; cur = cur.next
6return false
state
  • cycle??

line 1Does this list loop forever? The red arrow makes node 3 point BACK to node 1 — a walker never reaches ∅. Obvious fix: remember every node you visit.