Fast and Slow pointers Flashcards

(6 cards)

1
Q

What is the Fast & Slow Pointers pattern and when is it used?

A

Uses two pointers moving at different speeds to detect cycles or midpoints.

Use Case: Linked list cycles, midpoints, or palindromes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the key steps in the Fast & Slow Pointers technique?

A
  1. Initialize slow/fast pointers at head.
  2. Move slow by 1, fast by 2 until meet or end.
  3. Analyze meeting point (e.g., cycle exists).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does the Fast & Slow Pointers technique apply to Detect Cycle?

A

Detect cycle in linked list.
Approach: Fast pointer moves twice as fast; meeting indicates cycle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the complexity and gotchas of the Fast & Slow Pointers technique?

A

Time: O(n), Space: O(1).
Gotchas: No cycle, single node.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Code example for Fast & Slow Pointers.

A

```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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Visual: [Add image manually].

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly