Skip to content
Feb 28

Sliding Window on Arrays

MT
Mindli Team

AI-Generated Content

Sliding Window on Arrays

Mastering the sliding window technique is a fundamental leap in your algorithmic problem-solving skills, transforming problems that seem to require time into elegant solutions. This approach is indispensable for efficiently analyzing contiguous sequences—be it finding the longest substring with unique characters, the smallest subarray exceeding a sum, or the maximum average in a data stream. By maintaining a dynamic view over a portion of an array or string, you learn to trade brute-force computation for intelligent state management, a pattern that surfaces frequently in coding interviews and real-world data processing tasks.

Core Concept: The Sliding Window Paradigm

A sliding window is a conceptual range defined by two pointers (often indices left and right) that bound a contiguous subarray within a larger array. Instead of recalculating properties for every possible subarray from scratch, the window "slides" across the data, updating its internal state incrementally as elements enter and exit the window. This incremental update is the heart of its efficiency. The technique primarily manifests in two forms: fixed-size windows, where the length is constant, and variable-size windows, which expand and contract based on problem constraints. Understanding when and how to adjust these pointers allows you to solve complex subarray and substring problems in linear time, a significant improvement over naive nested-loop approaches.

Fixed-Size Windows: Computing Running Statistics

A fixed-size window maintains a constant length k as it slides from the start to the end of an array. This is ideal for problems asking for a property—like sum, average, maximum, or minimum—of every contiguous block of k elements.

Consider the classic problem: Find the maximum sum of any contiguous subarray of size k. A naive solution would use nested loops, leading to time complexity. The sliding window reduces this to .

Algorithm & Worked Example: Given array nums = [5, 2, -1, 6, 3, 1] and k = 3.

  1. Calculate Initial Window Sum: Sum of first k elements: window_sum = 5 + 2 + (-1) = 6. Set max_sum = 6.
  2. Slide the Window: Iterate right pointer from k to the end of the array (right = 3).
  • New element entering: nums[right] = 6.
  • Old element leaving: nums[right - k] = nums[0] = 5.
  • Update window_sum = window_sum + 6 - 5 = 7.
  • Update max_sum = max(6, 7) = 7.
  1. Continue Sliding: For right = 4 (element 3, leaving element 2): window_sum = 7 + 3 - 2 = 8. max_sum = 8.
  2. Final Slide: For right = 5 (element 1, leaving element -1): window_sum = 8 + 1 - (-1) = 10. max_sum = 10.

The key is to avoid recalculating the entire sum. By subtracting the element that falls out of the left side and adding the new element on the right, you maintain a running statistic with constant-time updates per step.

Variable-Size Windows: Dynamic Expansion and Contraction

Variable-size windows are used when you're searching for an optimal subarray (shortest, longest) that meets a certain condition, such as "sum greater than or equal to a target." The window expands to try to meet the condition and contracts to try to find a more optimal (e.g., smaller) solution.

The canonical problem is: Find the length of the smallest contiguous subarray whose sum is at least a target value S.

Algorithm & Worked Example: Given nums = [2, 1, 5, 2, 3, 2] and S = 7.

  1. Initialize: left = 0, current_sum = 0, min_length = Infinity.
  2. Expand the Window (outer loop with right pointer):
  • right = 0: current_sum = 2. Sum < 7.
  • right = 1: current_sum = 3. Sum < 7.
  • right = 2: current_sum = 8. Sum >= 7. Condition met!
  1. Contract the Window (inner while loop): Try to shrink from the left to see if a smaller valid window exists.
  • Current window: [2, 1, 5], length = 3. Update min_length = 3.
  • Move left to 1: current_sum = 8 - 2 = 6. Sum < 7. Stop contracting.
  1. Continue Expanding: right = 3: current_sum = 6 + 2 = 8. Sum >= 7.
  2. Contract Again:
  • Current window: [1, 5, 2], length = 3. min_length remains 3.
  • Move left to 2: current_sum = 8 - 1 = 7. Sum >= 7. New window [5, 2], length = 2. Update min_length = 2.
  • Move left to 3: current_sum = 7 - 5 = 2. Sum < 7. Stop.
  1. Final Expansion: Continue process through right = 4, 5. The smallest length found is 2 (subarray [5, 2] or [3, 2, 2]).

This expand-contract pattern ensures you examine every viable subarray in time.

Advanced State Tracking: Hash Maps for Complex Constraints

For problems with more complex constraints—like "longest substring with at most K distinct characters" or "subarray sum equals K"—simple running sums are insufficient. Here, window state tracking with a hash map (or dictionary) is essential to manage counts or frequencies of elements within the window.

Example Problem: Longest substring with at most 2 distinct characters in string "eceba". We treat the string as an array of characters.

  1. Initialize: left = 0, max_len = 0, char_count = {} (hash map).
  2. Expand (right from 0 to 4):
  • right=0 ('e'): Map = {'e':1}. Distinct = 1. Length=1.
  • right=1 ('c'): Map = {'e':1, 'c':1}. Distinct = 2. Length=2. max_len=2.
  • right=2 ('e'): Map = {'e':2, 'c':1}. Distinct = 2. Length=3. max_len=3.
  • right=3 ('b'): Map = {'e':2, 'c':1, 'b':1}. Distinct = 3 > 2. Condition violated.
  1. Contract (while distinct > 2):
  • Remove s[left] ('e') from map: {'e':1, 'c':1, 'b':1}. Distinct still 3.
  • left = 1. Remove s[left] ('c'): {'e':1, 'b':1}. Distinct = 2. Stop.
  1. Resume Expansion: Continue. The final max_len is 3 (window "ece").

The hash map allows us to instantly check the constraint (number of distinct keys) and correctly shrink the window by decrementing counts until a character's count reaches zero, at which point it is removed from the map.

Common Pitfalls

  1. Incorrect Window Shrink/Expand Logic: A frequent error is moving the left pointer too much or too little during contraction. In variable window problems, you must shrink only while the condition is still satisfied (for "at most" problems) or until it is just violated (for "at least" problems) to find the boundary of the valid window. Always double-check your loop's condition.
  2. Forgetting to Update State on Window Move: When the window slides, you must update your tracking variables twice: once for the element entering and once for the element exiting. A common bug is to add the new element but forget to remove the old one, corrupting the window's state for all subsequent steps.
  3. Off-by-One Errors with Indices: Be meticulous about whether your right pointer index is inclusive or exclusive in your window definition, and whether you initialize it at 0 or k-1. This affects your loop boundaries and calculations for window length, which is typically right - left + 1 for inclusive indices.
  4. Ignoring Edge Cases: Always test with empty arrays, window sizes (k) larger than the array length, target sums that are impossible to achieve, or arrays with all negative numbers (for sum-related problems). These scenarios often expose flaws in initialization or termination logic.

Summary

  • The sliding window technique uses two pointers to maintain a dynamic view of a contiguous subarray, enabling efficient solutions to problems that might otherwise require time.
  • Fixed-size windows slide a constant-length frame across the array, using incremental updates to compute running statistics like maximum sum or average without recalculation.
  • Variable-size windows dynamically expand to meet a condition (e.g., sum >= target) and contract to find an optimal solution (e.g., the smallest such subarray), following a predictable expand-and-shrink pattern.
  • For problems involving uniqueness or complex frequency constraints, window state tracking with a hash map is essential to manage counts of elements within the window and determine when to adjust its boundaries.
  • Success with this pattern hinges on careful pointer management, correct incremental state updates, and rigorous testing of edge cases to avoid off-by-one errors and incorrect contraction logic.

Write better notes with AI

Mindli helps you capture, organize, and master any subject with AI-powered summaries and flashcards.