DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

🪟 Sliding Window Explained Like You're 5

Moving window across data

Day 108 of 149

👉 Full deep-dive with code examples


The Train Window Analogy

Imagine looking out a train window:

  • You see a fixed portion of the scenery
  • As the train moves, the view changes
  • Old scenery slides out left, new scenery slides in right
  • But the window size stays the same

Sliding Window is like that train window!

You look at a fixed-size chunk of data and slide it along.


The Problem It Solves

Finding things in a sequence can be slow:

  • "Find the maximum sum of any 5 consecutive numbers"
  • "Find the longest substring without repeating characters"

The brute force way:

  • Check every possible group one by one
  • Recalculate everything from scratch each time
  • Very slow for large data

How Sliding Window Fixes It

Instead of recalculating everything:

  1. Calculate once for the first "window"
  2. Slide the window by one position
  3. Subtract what left, add what entered
  4. No need to recalculate the whole thing!
Numbers: [1, 3, 2, 6, 4, 1, 8, 2]
Window size: 3

Window 1: [1, 3, 2] → Sum = 6
Window 2:    [3, 2, 6] → Sum = 6 - 1 + 6 = 11
Window 3:       [2, 6, 4] → Sum = 11 - 3 + 4 = 12
Enter fullscreen mode Exit fullscreen mode

See? We just add and subtract, not recalculate!


When To Use It

Use sliding window when you need to:

  • Find something in a contiguous chunk of an array
  • Track a substring in a string
  • Compare consecutive elements

In One Sentence

Sliding Window efficiently processes data by sliding a fixed-size frame through it, updating as you go instead of recalculating everything.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)