Fast and Slow pointers Flashcards
(6 cards)
What is the Fast & Slow Pointers pattern and when is it used?
Uses two pointers moving at different speeds to detect cycles or midpoints.
Use Case: Linked list cycles, midpoints, or palindromes.
What are the key steps in the Fast & Slow Pointers technique?
- Initialize slow/fast pointers at head.
- Move slow by 1, fast by 2 until meet or end.
- Analyze meeting point (e.g., cycle exists).
How does the Fast & Slow Pointers technique apply to Detect Cycle?
Detect cycle in linked list.
Approach: Fast pointer moves twice as fast; meeting indicates cycle.
What are the complexity and gotchas of the Fast & Slow Pointers technique?
Time: O(n), Space: O(1).
Gotchas: No cycle, single node.
Code example for Fast & Slow Pointers.
```python
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, next: ‘ListNode’ = None):
self.val = val
self.next = next
def has_cycle(head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
~~~
Visual: [Add image manually].