Skip to main content

Sliding Window

Sliding Window is a technique to solve problems similar to the two pointer technique, with addition, sliding window also takes account whatever element inside the left and right pointer.

In two pointers, we have two variables that point to some data structure or sequence. We can use the variables to access the data structure at the same time, to reduce iteration. On the other hand, in sliding window technique, the two pointers are utilized as a boundary within the data structure we are examining. The elements inside that boundary is called a window, which can be analyzed or processed depending on the problem.

Here is an illustration:

For example, we can increment the left and right pointer to move the window, increase the window size by incrementing only the right pointer, decrease the window size by incrementing only the left pointer.

Example Algorithm

Here is a pseudocode example of sliding window algorithm that obtain a window of given size in an array.

function slidingWindow(arr: Array, windowSize: Int)
leftPointer = 0
rightPointer = leftPointer + windowSize - 1

while (rightPointer < size of arr):
leftPointer = leftPointer + 1
rightPointer = rightPointer + 1