Fast and Slow Pointers Flashcards
1
Q
- Linked List Cycle
Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.
O(n)
O(1)
A
Takeaway:
- Remember the while condition.
- Re-initialization condition.
- In the loop, slow and fast pointer equality must be checked after moving slow and faster pointers.
Pseudo code:
- Declare two instance variable of ListNode named as slow, fast.
- Initialize slow and fast both to head.
- Iterate through while loop until fast is not null and fast.next is not null.
- Re-initialize fast with fast.next.next, slow with slow.next.
- If slow and fast are same return true.
- In the last return false.