If we constraint the input of Finding Duplicates to:
NOTE
input array with
then we can use a better algorithm with time and memory
Overview
The idea is to start with the two pointers slow and fast, both starting at the head of the linked list.
- While traversing the List:
- slow pointer will move one step at a time.
- fast pointer moves two steps at a time.
- If there’s a cycle, the fast pointer will eventually catch up with the slow pointer within the cycle because it’s moving faster.
- If there’s no cycle, the fast pointer will reach the end of the list (i.e., it will become NULL).
- When the slow and fast pointers meet, a cycle or loop exists
Application
Given: Array with Goal: Find two indices with Constraints: time , memory We observe the graph with
We observe the subgraph (nodes and edges that are reachable from )floyd's cycle finding example.excalidraw
⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠ You can decompress Drawing data with the command palette: ‘Decompress current Excalidraw file’. For more info check in plugin settings under ‘Saving’
Excalidraw Data
Text Elements
n
Link to original
We define Claim: There is such that Proof: Let so andfloyd's cycle finding example Dn.excalidraw
⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠ You can decompress Drawing data with the command palette: ‘Decompress current Excalidraw file’. For more info check in plugin settings under ‘Saving’
Excalidraw Data
Text Elements
n
Link to original
Now we can use the two pointers to solve the task.
Find
slow=a[n]
fast=a[a[n]]
t=1
while(slow!=fast)
slow=a[slow]
fast=a[a[fast]]
t=t+1
Claim: Let with then Proof: for some for some
find with
fast=n
while(slow!=fast)
i=slow
j=fast
slow=a[slow]
fast=a[fast]
return i,j