Sliding window
A sliding window maintains a contiguous segment of an array or string. You grow or shrink the segment as you scan, so each element enters and leaves at most once.
Detailed Explanation
Many problems ask about a substring or a subarray: longest without repeating characters, minimum window covering a set of letters, maximum sum of k consecutive elements. A nested loop that picks every pair of ends is O(n²) or worse. A window uses two indexes, left and right. right advances through the data. When the window breaks a rule, left advances to fix it.
The invariant is the point. Example: "longest substring without repeats". The window holds unique characters. When right sees a duplicate, move left until that character is gone, then add the new one. A Map or a count array records what the window contains so you do not rescan it.
Fixed-length windows are simpler. Sum of each block of k: add xs[right], subtract xs[right - k] once right >= k. That is O(n) after the first block.
You reach for a sliding window when the answer is a contiguous segment and the condition is monotonic: making the window larger never fixes a "too many distinct" constraint, so you only shrink from the left. You keep two pointers that are not a window when the pair is not contiguous. You keep prefix sums when the question is about sums of many ranges, not about a single growing segment.
The cost of a wrong invariant is an O(n²) inner while that can run back to 0 every time. left must only move forward. The cost of using a hash map of indexes is forgetting to ignore stale indexes that fell out of the window. Store counts, or check that the stored index is still >= left.
Strings of ASCII can use int[256] instead of a map. Unicode needs a map of code points. Empty input and k > n need explicit answers.
Code Examples
import java.util.HashMap;
import java.util.Map;
public class LongestUnique {
static int length(String s) {
Map<Character, Integer> last = new HashMap<>();
int left = 0;
int best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (last.containsKey(c) && last.get(c) >= left) {
left = last.get(c) + 1; // shrink past the previous c
}
last.put(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(length("abba")); // prints: 2
System.out.println(length("abcabcbb")); // prints: 3
}
}public class MaxSumK {
static int maxSum(int[] xs, int k) {
int sum = 0;
for (int i = 0; i < k; i++) {
sum += xs[i];
}
int best = sum;
for (int i = k; i < xs.length; i++) {
sum += xs[i] - xs[i - k];
best = Math.max(best, sum);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxSum(new int[] {2, 1, 5, 1, 3, 2}, 3)); // prints: 9
}
}Common Gotchas
`left` must never decrease
an inner loop that resets `left` to 0 destroys the O(n) bound.
Stale map indexes from before `left`
treat them as absent, or store counts instead of last-seen indexes.
Fixed `k` greater than `n` needs a defined policy
throw, or return the sum of the whole array.
The condition must be shrinkable from the left
if a larger window can become valid again without shrinking, window is the wrong tool.