Fast & Slow Pointers vs Two Pointers vs Sliding Window
Fast & Slow Pointers, Two Pointers, and Sliding Window are powerful patterns for solving coding problems using indexes or pointers. Although they may look similar, each pattern uses pointers differently and is designed for different types of problems. Let's consider the key principles of each pattern, how the pointers move, and the main differences between Fast & Slow Pointers, Two Pointers, and Sliding Window.
In Sliding Window, left/right represent a range [left, right] whose state we maintain. In Fast & Slow Pointers, the relationship between the pointers' speeds and positions is what matters. In the classic Two Pointers pattern, we use the interaction between two positions to avoid a full brute-force search.
By the way, Fast & Slow Pointers is often considered a subtype of the Two Pointers pattern, while Sliding Window is usually treated as a separate pattern.
I've added links to separate articles about each pattern, where you can explore each pattern in detail and find relevant LeetCode problems to practice.
Two Pointers
The pointers move toward each other or in the same direction.
int left = 0;
int right = n - 1;
while(left < right)
{
if (...)
left++;
else
right--;
}Fast & Slow Pointers
The pointers move in the same direction but with the different speed.
int slow = 0;
int fast = 0;
while(fast < n)
{
slow++;
fast += 2;
}Sliding Window pattern
Left and right pointers define the current window. We can expand and shrink the window.
int left = 0;
for (int right = 0; right < n; right++)
{
// expand window
while (...)
{
// shrink window
left++;
}
}