Sliding Window
Lesson 10Beginner46 minAssessment-backed

Sliding Window

Maintain a moving contiguous range for arrays, strings, streams, rate limits, and bounded product windows.

What you will be able to do

Explain sliding window as a range plus maintained state.
Distinguish fixed-size and variable-size windows.
Implement variable-window logic with expand, shrink, and record phases.
Apply the pattern to rate limits, analytics windows, and substring problems.

Sliding window is the pattern for contiguous ranges when recomputing from scratch would waste work. Instead of asking every possible range independently, you keep a live range and update its state as the range moves.

A Window Is a Range Plus State

A window has boundaries, usually left and right, and state such as sum, count, frequency map, max length, violation count, or current cost. The engineering advantage is incremental update: when the right side expands, add one item; when the left side shrinks, remove one item.

Sliding window phases
Each item enters the window once and leaves once. That is why many variable-window algorithms are O(n), not O(n^2).

Scenario: API Rate Limit Window

A service allows 100 requests per user in any 60-second window. A naive implementation might scan all historical requests for every new request. A windowed design keeps only recent timestamps, removes expired ones, and checks the current count.

Real-world usage

Sliding windows power rate limiters, fraud burst detection, rolling metrics, session analytics, audio/video buffers, recent-search features, and substring validation.

Variable Window in Java, Python, and JavaScript

The following function finds the longest subarray with sum at most a budget when values are non-negative. Non-negative values matter because expanding only increases the sum and shrinking only decreases it.

class LongestBudgetWindow {
    static int longestAtMost(int[] costs, int budget) {
        int left = 0;
        int sum = 0;
        int best = 0;
        for (int right = 0; right < costs.length; right++) {
            sum += costs[right];
            while (sum > budget) {
                sum -= costs[left];
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Fixed vs Variable Windows

Window typeUse whenExample
Fixed sizeThe range length is givenAverage CPU over the last 5 samples.
Variable sizeThe range expands and shrinks based on validityLongest substring under a constraint.
Time windowItems expire by timestampRequests in the last 60 seconds.

Assessment trap

Sliding window is usually for contiguous ranges. If the selected items can be non-contiguous, you may need a different pattern.

Field judgmentEngineering Notes

  • Define what makes the window valid.
  • Define what state is maintained.
  • Explain why each element enters and leaves at most once.
  • For negative numbers, sum-window assumptions can fail.
  • Tie window state to product constraints like time, budget, length, or uniqueness.

Interview signalFrequently Asked Interview Questions

These are canonical interview patterns for this topic, phrased as concrete problem statements. They avoid vague theory questions and prepare you for the exact reasoning interviewers expect: invariant, edge cases, complexity, and trade-off.

  • Return the length of the longest substring containing at most k distinct characters.
  • Given non-negative costs, return the longest contiguous subarray with total cost at most budget.
  • Allow a request only if the user has fewer than limit requests in the last 60 seconds.

Production practiceCompany-Style Practice Examples

These are not claimed as exact company-specific questions. They are the interview patterns repeatedly used by product companies to test whether you can move from brute force to a defensible implementation.

ExampleBrute-force approachStronger solutionProduction notes
Longest substring without repeatsCheck every substring with a set.Maintain a window and last seen positions or frequency map.Each character enters/leaves bounded times.
Rate limiterScan all historical requests per request.Maintain timestamps inside a rolling time window.Expire old entries before checking count.
Longest budget subarrayTry every start/end range.Expand right and shrink left while sum exceeds budget.Requires non-negative values for monotonic behavior.

Solved modelInterview Question Solutions

Question 1: Longest Substring With At Most K Distinct Characters

Return the length of the longest substring containing at most k distinct characters. Brute force checks every substring. Sliding window maintains character counts and shrinks from the left while the distinct count is too large.

import java.util.*;

class LongestKDistinct {
    static int longest(String s, int k) {
        Map<Character, Integer> counts = new HashMap<>();
        int left = 0;
        int best = 0;

        for (int right = 0; right < s.length(); right++) {
            char add = s.charAt(right);
            counts.put(add, counts.getOrDefault(add, 0) + 1);

            while (counts.size() > k) {
                char remove = s.charAt(left++);
                counts.put(remove, counts.get(remove) - 1);
                if (counts.get(remove) == 0) counts.remove(remove);
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Question 2: Longest Subarray Under Budget

Given non-negative costs, return the longest contiguous subarray with total cost at most budget. Because values are non-negative, expanding increases or preserves total and shrinking decreases or preserves it. That monotonic behavior makes sliding window valid.

class BudgetSubarray {
    static int longest(int[] costs, int budget) {
        int left = 0, sum = 0, best = 0;
        for (int right = 0; right < costs.length; right++) {
            sum += costs[right];
            while (sum > budget) {
                sum -= costs[left];
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Question 3: 60-Second Rate Limiter

Allow a request only if the user has fewer than limit requests in the last 60 seconds. Keep a per-user queue of timestamps. Before accepting a request, remove expired timestamps, then check the active count.

import java.util.*;

class RateLimiter {
    private final Map<String, Deque<Long>> byUser = new HashMap<>();

    boolean allow(String userId, long nowMs, int limit) {
        Deque<Long> window = byUser.computeIfAbsent(userId, _id -> new ArrayDeque<>());
        long cutoff = nowMs - 60_000;
        while (!window.isEmpty() && window.peekFirst() <= cutoff) {
            window.removeFirst();
        }
        if (window.size() >= limit) return false;
        window.addLast(nowMs);
        return true;
    }
}

Solved modelWorked Interview Answer

Find the longest contiguous subarray with sum at most a budget when all values are non-negative. Maintain a valid window. Non-negative values make shrinking safe because removing from the left cannot increase the sum.

class BudgetWindow {
    static int longestAtMost(int[] costs, int budget) {
        int left = 0, sum = 0, best = 0;
        for (int right = 0; right < costs.length; right++) {
            sum += costs[right];
            while (sum > budget) sum -= costs[left++];
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}

Hands-on drillTry It Yourself

Practice task

Implement a variable window. Label the expand step, maintained state, invalid condition, shrink step, and best-answer update.

Failure patternsCommon Mistakes to Avoid

  • Using sliding window for non-contiguous selections.
  • Forgetting to remove state when the left pointer moves.
  • Applying sum-window logic with negative numbers without checking whether monotonic shrink still works.

Execution guardrailQuick-Start Checklist

  • Define the window boundaries.
  • Define the maintained state.
  • Define when the window is valid.
  • Shrink until valid.
  • Record the answer at the correct time.

Recall drillKnowledge Check

QuestionStrong answer
Why is sliding window often O(n)?Each item enters the window once and leaves once.
What makes a window valid?A constraint such as sum, length, distinct count, time, or budget.
Why can negative numbers break sum windows?Expanding and shrinking no longer change the sum monotonically.

VocabularyKey Terms

TermMeaning
WindowA contiguous active range in a sequence.
ExpandMove the right boundary to include a new item.
ShrinkMove the left boundary to restore validity.

Next practiceFurther Reading

  • Practice longest substring without repeating characters.
  • Study rate limiters and rolling metrics.
  • Compare sliding window with prefix sums for range problems.