Sliding Window
Learn Sliding Window (Arrays, Data Structures & Algorithms) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.
What is the Sliding Window Pattern? Sliding window solves problems about a contiguous range (subarray/substring) by maintaining a window with two pointers, left and right , and sliding it across the array instead of recomputing from scratch for every position. Fixed-size window: the window size k never changes - slide it one step at a time, subtracting the element leaving and adding the element entering. Variable-size window: grow the window by moving right ; shrink it by moving left whenever a condition is violated. Both turn an O(n·k) or O(n²) brute force into O(n).