Day 73: :mag: The Sliding Window Technique — Why It’s a Must-Know for Every LeetCoder

Let’s say you’re given this simple problem:

:point_right: “Find the maximum sum of any 3 consecutive numbers in an array.”

You have this array:

js

nums = [1, 2, 3, 4, 5, 6]

The brute-force way?

Check all groups of 3:

1+2+3 = 6

2+3+4 = 9

3+4+5 = 12

4+5+6 = 15

:white_check_mark: Answer: 15

:x: But time complexity = O(n * k) if k is the window size.

Now imagine your array has 1 million numbers and you need the sum of every 1000 consecutive numbers — suddenly, brute force isn’t so cute.

Enter the Sliding Window Technique.

:bulb: How It Works

You build a “window” of size k (in this case, 3), calculate the sum once, and then just “slide” the window one step at a time:

Initial sum: 1 + 2 + 3 = 6

Slide window right:

Remove 1 (leftmost)

Add 4 (next in array)

→ New sum: 6 - 1 + 4 = 9

Repeat:

Remove 2, add 5 → 9 - 2 + 5 = 12

Remove 3, add 6 → 12 - 3 + 6 = 15

Same result, but in O(n) time.

:dart: This is what Sliding Window does:

It avoids repetition by reusing previous calculations and only adjusting what changed — making it a go-to for efficient algorithms.

:key: Where You’ll Use It on LeetCode

The Sliding Window technique shines in problems involving:

Subarrays or substrings

Consecutive or fixed-size elements

Dynamic tracking (length, sum, uniqueness)

:boom: Examples:

Longest Substring Without Repeating Characters

Maximum Sum Subarray of Size K

Minimum Size Subarray Sum

Permutation in String

Contains Duplicate II

:eyes: Visualize It Like This:

Imagine dragging a box across your array or string.

At every move, you only care about the element that enters and the one that exits.

The rest of the window stays intact — so your calculations are fast, clean, and focused.

:brain: When to Reach for Sliding Window:

The question mentions “subarray” or “substring”

You’re given a length or range constraint

You need to find “maximum/minimum/longest/shortest” something

Brute force is too slow, and you want to cut it to O(n)

:dart: From Two Pointers to Sliding Window

If you’ve mastered the Two Pointer approach, Sliding Window is your next step.

They’re cousins — both involve scanning with two markers — but Sliding Window is like a smarter version that carries memory with it.

You don’t restart; you slide.