Introduction

The sliding window algorithm is generally used on problems that look for some max, min, or target value in a contiguous sequence within an array. It is often some kind of optimal, like the longest sequence or shortest sequence of something that satisfies a given condition exactly.

How to identify?

But the biggest giveaway is that the thing you are looking for is often some kind of optimal, like the longest sequence or shortest sequence of something that satisfies a given condition exactly.

Characteristics of the problems that can be solved by two pointers. The summary is simple:

  1. If a wider scope of the sliding window is valid, the narrower scope of that wider scope is valid mush hold.
  2. If a narrower scope of the sliding window is invalid, the wider scope of that narrower scope is invalid mush hold.

Approaches

The window represents the current section of the string/array that you are “looking at” and usually there is some information stored along with it in the form of constants. At the very least it will have 2 pointers, one indicating the index corresponding beginning of the window, and one indicating the end of the window.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a1778e3a-01bf-40b8-ae90-6d037ddf0b81/Untitled.png

Basic pattern:

The basic pattern which is used for questions with single array/string input, where dynamic frequency map can be calculated on the fly.

Like:

Fruits into baskets

  1. Create frequency map.
  2. Increment character/number frequency with end pointer.
  3. Check a condition.
  4. Remove element with start pointer if it's frequency is 0.