3
2
0
-4
[0][1][2][3]
Brute force · visited set
▸1given head2visited = {}3cur = head; while cur ≠ ∅:4 if cur in visited: return true5 add cur; cur = cur.next6return false
state
- cycle??
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 problemGiven 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.
▸1given head2visited = {}3cur = head; while cur ≠ ∅:4 if cur in visited: return true5 add cur; cur = cur.next6return false
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.