03. Fast and Slow Pointers
Theory
Description
The Fast and Slow Pointer technique, also called the Tortoise and Hare algorithm, is a powerful method for efficiently solving problems in linked lists and cyclic structures.
How It Works
- The slow pointer moves one step at a time.
- The fast pointer moves two steps at a time.
The difference in speeds allows the fast pointer to catch up with the slow pointer if there’s a cycle or to identify the middle of a structure.
Key Insights
- Cycle Detection: If a cycle exists, the fast pointer will meet the slow pointer inside the cycle.
- Middle Element: The slow pointer will be at the middle when the fast pointer reaches the end.
- Pattern Matching: Helps detect patterns like palindromes by dividing the structure into two parts.
Benefits
- Time Efficient: Solves problems in O(n) time with a single traversal.
- Space Efficient: Requires O(1) space, avoiding extra data structures.
- Simple & Elegant: Reduces complex problems to simple solutions.
Problems
1. Linked List Cycle (Leetcode:141)
Problem Statement
Code and Explaination
2. Linked List Cycle II (Leetcode:142)
Problem Statement
Code and Explaination
3. Happy Number (Leetcode:202)
Problem Statement
Code and Explaination
4. Middle of the Linked List (Leetcode:876)
Problem Statement
Code and Explaination
5. Palindrome Linked List (Leetcode:234)
Problem Statement
Code and Explaination
Explaination:
This is first approach
Explaination:
This is second approach
This is second approach
6. Reorder List (Leetcode:143)
Problem Statement
Code and Explaination
7. Circular Array Loop (Leetcode:457)
Problem Statement
Code and Explaination
8. Remove Nth Node From End of List (Leetcode:19)
Problem Statement
Code and Explaination
9. Rotate List (Leetcode:61)
Problem Statement
Code and Explaination
10. Find the Duplicate Number (Leetcode:287)
Problem Statement
Code and Explaination
11. Moving Stones Until Consecutive II (Leetcode:1040)
Problem Statement
Code and Explaination
12. Remove Duplicates from Sorted List II (Leetcode:82)
Problem Statement
Code and Explaination
13. Friends Of Appropriate Ages (Leetcode:825)
Problem Statement
Code and Explaination
14. Partition Labels (Leetcode:763)
Problem Statement
Code and Explaination
15. Longest Mountain in Array (Leetcode:845)
Problem Statement
Code and Explaination
16. Count Pairs Of Nodes (Leetcode:1782)
Problem Statement