Sliding Window — A common technique to solve algorithmic problems involving String/Array

Long Nguyen
The Startup
Published in
6 min readDec 30, 2019

--

An illustration of a fixed window frame being slid from left to right of an array of numbers
An illustration of a fixed-size sliding window

Hello World!

I recently came across the Sliding Window technique while trying to solve a few algorithmic problems involving arrays or strings. Being a subset of Dynamic Programming, it is a really powerful technique and is usually used along with data structure like Hash Map, Hash Set or Array. I’m no master at this but after attempting a few problems with this method, I thought I might share what I have learnt so far.

Why the name Sliding Window?

This technique itself involves 2 pointers (usually indices of string/array) representing 2 edges on the side of the window — start index is on the left edge and end index is on the right edge. The elements of the array captured inside the range of the start and end indices will be used to calculate the result.

Based on certain conditions or constraints of the problem, the window can be extended (by increasing the right pointer) or shrunk (by increasing the left pointer). As a result, the window begins to slide from start to finish of the array, scanning all elements. Hence the name, sliding window.

Why use Sliding Window?

--

--