Algorithms · 372 words · 2 minute read
Sliding Window in Java: Fixed Windows, Variable Windows, and Deques
By Priyanshu Rauth · Published 2026-09-04 · Updated 2026-09-04
A sliding window represents a contiguous range that moves through an array or String. It is useful when neighboring candidate ranges overlap heavily. Instead of rebuilding a sum or count for each range, remove the element leaving the window and add the element entering it. The hard part is not the syntax; it is defining exactly when the window is valid and when it must shrink.
Fixed-size windows
For a window of size k, build the first k values once. Every later move subtracts the value at right - k and adds the new right value. That turns a naive O(nk) calculation into O(n). Validate k before allocating output or dividing by it: k must be positive and no greater than the input length.
public class Main {
static int bestSum(int[] values, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += values[i];
int best = sum;
for (int right = k; right < values.length; right++) {
sum += values[right] - values[right - k];
best = Math.max(best, sum);
}
return best;
}
public static void main(String[] args) {
System.out.println(bestSum(new int[] {2, 1, 5, 1, 3, 2}, 3));
}
}The output is 9, from the window 5, 1, 3. The loop never recomputes a window sum from scratch.
Variable windows and monotonic deques
For “longest range satisfying a rule,” grow right until the rule fails, then advance left until it holds again. The data structure holding the rule’s state might be a frequency map or count. For a maximum in every fixed window, a deque of candidate indices can do better than rescanning: discard expired indices from the front and smaller values from the back.
Common mistakes
- Forgetting to remove the outgoing value before recording a new fixed window.
- Allowing k equal to zero or greater than the input length.
- Shrinking only once when a constraint may require repeated shrinking.
- Storing deque values instead of indices, which makes expiration ambiguous.
Practice next
Start with maximum subarray sum to distinguish a dynamic subarray from a fixed window. Then solve sliding window maximum and compare its deque invariant with the simpler running-sum example. Continue to longest substring with k distinct characters when you are comfortable updating a frequency map as pointers move.
Continue with the Java practice path · Try code in the Java compiler