Photo by Eric Prouzet on Unsplash

Okay, Move Along

The Fixed-Size Sliding Window Pattern/Technique

Jamie Berrier
2 min readFeb 7, 2021

--

The fixed-size sliding window pattern optimizes algorithms that involve searching an array or string for a consecutive subsection, of a given size, that satisfies a given condition. It can also be considered a variation of the two pointers pattern.

To solve problems like these, we could apply a brute force solution with a nested loop, but it would produce O(n²) time complexity at best. Applying the fixed-size sliding window pattern can reduce the time complexity to O(n) and space complexity to O(1).

Let’s get a move on

In this pattern, two pointers create a window that represents the current subsection of the data structure. One pointer is the leading edge and the other pointer is the trailing edge. This window, or chunk, is evaluated to see if it satisfies the given condition. The window slides along the data structure (by incrementing the pointers) to create a new window. The new window is now evaluated to see if it satisfies the given condition.

Fixed Size Sliding Window

The window continues to slide until the leading edge reaches the end. Once the window has reached the end, the requested output is returned.

We are moving in the right direction when the problem:

  • involves a data structure that is iterable (arrays, strings, etc.)
  • has a size constraint (e.g. of given length k)
  • asks to find a subsection (substring/subarray) that meets a desired condition/target value (e.g. max/min)

Example

maxSubArraySum

Sample Problems

📚 Resources 👀

Coding Patterns: Sliding Window

JavaScript Sliding Window Technique — Fixed Size

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response