Sliding Window
Sliding Window
The sliding window algorithm is a common technique used to solve problems involving sequences
by creating a "window" that can expand and contract over the data structure. This approach is
optimizing algorithms that would otherwise involve nested loops, allowing you to solve problems in
linear time.
How It Works:
1. Initialization: Start with two pointers (usually referred to as 'start' and 'end') that define the current
window
2. Expansion: Move the 'end' pointer to expand the window and include more elements.
3. Contraction: When a condition is met (e.g., a specific sum is exceeded, or a duplicate is found),
4. Calculation/Output: During the iteration, you can keep track of metrics and update results
accordingly.
Applications:
Let's implement a sliding window algorithm in Java to find the length of the longest substring without
repeating characters.
import java.util.HashMap;
class Solution {
int maxLength = 0;
if (charIndexMap.containsKey(currentChar)) {
charIndexMap.put(currentChar, end);
return maxLength;