Recognizing sliding window

RoadmapsDSA

Overview

Recognizing when to use an elastic boundary over data to optimize continuous subsets in linear time.

The surface signal is a problem asking about a CONTIGUOUS subarray or substring with a size or optimality constraint. Both pointers move in the SAME direction, the window only grows/shrinks, and never resets to scan from scratch, guaranteeing O(n) execution.

Where used: TCP sliding windows regulate the number of unacknowledged bytes a sender can transmit, maximizing throughput while avoiding congestion., Streaming data analytics, calculating moving averages over fixed time intervals.

Why learn this

Common mistakes

Recall questions

Understanding checks

You need to find the longest subarray that sums to exactly K, but the array contains BOTH positive and negative integers. Should you use a variable sliding window?

No. Sliding window requires monotonic growth/shrink properties. Adding a negative number decreases the sum, breaking the rule that 'expanding the window always increases the state.' You must use a Prefix Sum with a Hash Map instead.

Recognizing when negative constraints destroy the monotonic invariant is the most common way engineers pass or fail sliding window interviews.

A developer is trying to find the longest common subsequence between two strings and immediately starts setting up left and right pointers to form a sliding window. What is the fundamental flaw?

A subsequence is NOT contiguous. A sliding window physically cannot model gaps. This is a classic overlapping subproblems scenario requiring 2D Dynamic Programming.

Conflating 'substring' (contiguous) with 'subsequence' (gaps allowed) leads to applying the entirely wrong algorithmic pattern.

Practice tasks

Fix the O(n^2) window reset

The provided code attempts a sliding window but inadvertently resets the left pointer, making it O(n^2). Fix the logic so the left pointer only moves forward, maintaining the O(n) bound.

Continue learning

Previous: Sliding window (fixed)

Previous: Sliding window (variable)

Previous: Kadane's algorithm

Next: Pattern recognition drill

Return to DSA Roadmap