All articles
Coding

Mastering the Sliding Window Pattern for Subarray Problems

Learn the sliding window technique to solve substring and subarray coding problems. Master the expand-and-shrink template for fixed and variable windows.

Published by Ansh Modi · Vrenic
11 min read
On this page
  1. Recognising a sliding window problem
  2. Fixed-length windows and the naive approach
  3. The variable-length window pattern
  4. The expand-and-shrink template
  5. Analysing time and space complexity
  6. Common pitfalls and how to avoid them
  7. Before your next coding round
{}CODING

Subarray and substring problems often lead candidates straight into nested loops, resulting in code that fails time constraints on large inputs. When an assessment asks for the longest, shortest, or target value of a contiguous sequence, iterating through every possible combination is rarely the intended solution. The sliding window technique turns these quadratic operations into a single linear pass. By tracking the state of a sequence as it moves across an array, you can solve these problems with optimal time complexity.

Recognising a sliding window problem

The primary signal for a sliding window approach is a requirement to process a contiguous sequence of elements. This manifests as a substring within a larger text string, or a subarray of numbers in a larger array. Problem statements generally ask you to optimise a specific metric based on a condition. You might need to find the longest sequence meeting a rule, the shortest sequence reaching a sum, or simply count all sequences of a specific length that match a target.

It is crucial to distinguish a contiguous sequence from a subsequence before writing any code. A contiguous sequence means the elements sit directly next to each other without any gaps. A subsequence allows you to skip elements as long as you maintain their relative order, which breaks the logic of a sliding window. If the problem allows skipping elements to form the target sequence, evaluating dynamic programming or a separate two-pointer technique is the correct path.

Constraints also affect whether the pattern applies. Finding a target sum using a variable sliding window only works if the array contains entirely non-negative integers. If the array contains negative numbers, adding an element might actually decrease the sum, which breaks the assumption that expanding the window always increases the total. In such cases, you must fall back to a prefix sum array combined with a hash map, rather than relying on the sliding window technique.

Fixed-length windows and the naive approach

Some technical questions explicitly state the size of the subarray you need to evaluate. For instance, you might be asked to find the maximum sum of any contiguous subarray of exactly length k. This is a fixed-length sliding window problem. Because the size of the window never changes, the logic for moving it across the data structure is highly predictable.

When the sequence must be contiguous, a brute-force approach generally uses an outer loop to set the starting position and an inner loop to process the elements up to the end position. If you evaluate every possible subarray, this generates a time complexity of O(N^2). Such inefficiencies will trigger time-limit exceed errors during an assessment. To illustrate, consider an array of temperatures where you need the highest sum over a three-day period.

Here is a weak, brute-force answer that a candidate might write when they first encounter this problem.

def max_fixed_window_naive(nums: list[int], k: int) -> int:
    if not nums or k <= 0 or k > len(nums):
        return 0
        
    max_sum = float('-inf')
    
    for i in range(len(nums) - k + 1):
        current_sum = 0
        for j in range(i, i + k):
            current_sum += nums[j]
            
        max_sum = max(max_sum, current_sum)
        
    return max_sum

This naive code recalculates the sum from scratch for every single subarray. The outer for loop resets the state, and the inner for loop iterates through the same middle elements repeatedly. If the temperatures are [10, 15, 20, 25, 30] and k is three, the first loop sums 10, 15, and 20. The next iteration steps forward by one and sums 15, 20, and 25. The middle elements, 15 and 20, are added together twice.

The sliding window pattern collapses those nested iterations by keeping the calculated work from the previous sequence and applying it to the next one. Instead of recalculating the entire window from scratch on each step, you only account for the elements that change. You add the new element entering the window on the right side and subtract the element leaving the window on the left side. The overlapping elements in the middle remain completely untouched.

Here is the strong answer, transforming the O(N^2) recalculation into an O(N) linear pass.

def max_fixed_window_optimal(nums: list[int], k: int) -> int:
    if not nums or k <= 0 or k > len(nums):
        return 0
        
    window_sum = sum(nums[:k])
    max_sum = window_sum
    
    for i in range(k, len(nums)):
        window_sum = window_sum - nums[i - k] + nums[i]
        max_sum = max(max_sum, window_sum)
        
    return max_sum

The transformation from weak to strong code relies on removing the inner loop entirely. In its place, an initialisation step handles the first k elements before the main loop begins, establishing a baseline state. Inside the new single loop, nums[i - k] represents the element falling out of the window, while nums[i] is the new element coming in. Subtracting the old and adding the new yields the updated total using just two basic arithmetic operations, completely bypassing the middle elements.

The variable-length window pattern

In many coding assessments, the window size changes dynamically based on the input data. You might need to find the longest subarray that sums to a value exactly equal to S, or the shortest substring containing all the vowels. The window expands and shrinks as it searches for the optimal sequence, lacking a predetermined length.

This dynamic movement requires two pointers: a right pointer to expand the window by adding new elements, and a left pointer to shrink the window when a constraint is violated. A state tracker monitors the current contents of the window between these two pointers. The type of state tracker you choose dictates how you evaluate the window's validity.

If the problem asks for a subarray sum, a simple integer serves as a running total. If the problem asks you to find an anagram, you will need a hash map representing the current window to compare against a target hash map. Managing these trackers accurately is the hardest part of the pattern, as the pointers rely entirely on this data to decide their next move.

Consider a problem asking for the longest substring with at most k distinct characters. A brute-force approach checks every possible starting and ending point, rebuilding a hash map to verify the distinct count for each one. The variable sliding window approach keeps exactly one hash map and dynamically updates it.

The right pointer steps forward one element at a time, feeding characters into the hash map. If the distinct character count exceeds k, the window is suddenly invalid. The left pointer then steps forward to remove characters from the map until the distinct count drops back down to k, restoring the window's validity.

The expand-and-shrink template

Mastering variable sliding windows means internalising a standard code structure that handles the pointer movements safely. Below is the expand-and-shrink template in Python applied to the problem of finding the longest substring with at most k distinct characters. This structure can be adapted for nearly any variable window problem.

def longest_substring_k_distinct(s: str, k: int) -> int:
    if not s or k == 0:
        return 0
        
    char_counts = {}
    max_length = 0
    left = 0
    
    for right in range(len(s)):
        right_char = s[right]
        char_counts[right_char] = char_counts.get(right_char, 0) + 1
        
        while len(char_counts) > k:
            left_char = s[left]
            char_counts[left_char] -= 1
            if char_counts[left_char] == 0:
                del char_counts[left_char]
            left += 1
            
        max_length = max(max_length, right - left + 1)
        
    return max_length

The logic follows a strict order of operations to ensure accuracy. The for loop drives the right pointer forward unconditionally, expanding the window by exactly one element and updating the state tracker. Next, a while loop checks if the window has violated the primary constraint.

If the constraint is broken, the left pointer moves forward, systematically removing elements from the state tracker until the condition is satisfied again. It is critical that the left pointer loop completely resolves the invalid state before moving on. The code guarantees that the window is valid by the time the while loop terminates.

Finally, the result variable is updated only after the window has been validated. Placing the max_length calculation at the very end of the loop prevents off-by-one errors. You ensure that the mathematical operation right - left + 1 only measures sequences that strictly obey the rules.

Analysing time and space complexity

At first glance, the variable window template looks like it has a quadratic time complexity because a while loop sits directly inside a for loop. However, time complexity is determined by how many total times an operation executes across the entire run, not strictly by the visual nesting of loops. This requires an amortised analysis of the pointer movements.

In the expand-and-shrink template, the right pointer iterates over every element in the array exactly once. The left pointer also iterates over the elements, moving strictly forward and never moving backward. The left pointer can never cross or outpace the right pointer.

This means every single element in the input structure is added to the window at most once and removed at most once. Two operations per element across N elements results in linear operations. Dropping the constant gives a true time complexity of O(N). You process the entire input in linear time.

Space complexity depends entirely on the data structure used for the state tracker. If you are tracking a running sum for a numeric array, the space complexity is O(1) because it only requires a few integer variables. If you are tracking character frequencies using a hash map, the space complexity is proportional to the size of the permitted alphabet.

For standard ASCII strings, the hash map will store at most 256 keys, capping the memory footprint and maintaining an O(1) space complexity. If the input domain is unbounded, or if you are tracking unique integers in a massive array, the state tracker might store every element. In those worst-case scenarios, the space complexity becomes O(N).

Common pitfalls and how to avoid them

Edge cases frequently break sliding window implementations during assessments. Always check for empty inputs or inputs that are mathematically smaller than the required window size. In the distinct characters example, if k is zero, returning zero immediately prevents the logic from entering a faulty state. Ensure your code returns the correct default value if the target condition is never met across the entire array.

Another common trap is updating the state tracker incorrectly when moving the left pointer. You must deduct the element at the left index from your state tracker precisely before incrementing the left variable. Reversing this order, or forgetting to delete a key when its frequency count reaches zero, will corrupt your state tracker and produce incorrect substring lengths.

Off-by-one errors are equally destructive, especially when calculating the length of the valid sequence. The length of a window spanning from index left to index right inclusive is always right - left + 1. Memorising this specific formula prevents you from undercounting the subarray length during a high-pressure interview.

To build confidence, trace your pointers using a small input array on paper before writing any code. Draw the array, mark the left and right indices, and update a tally of the state tracker for each step. This exposes logic gaps before they become difficult to debug on screen. When you are ready to test your implementation skills under pressure, you can use Vrenic Premium. The Premium plan includes proctored coding assessments where an AI-generated problem runs your code against test cases in your browser and is graded on correctness, complexity, code quality and approach.

Before your next coding round

Practise identifying the pattern in problem descriptions. Apply this checklist to determine if a sliding window is the correct approach and to structure your solution without missing steps.

  • Confirm the sequence must be contiguous before applying the pattern. If elements can be skipped to form the sequence, pivot to evaluating dynamic programming.
  • Decide whether the problem requires a fixed or variable window. Fixed windows are explicit in the prompt, whereas variable windows usually ask for a maximum, minimum, or target threshold.
  • Define what condition makes a variable window invalid. Write down the exact rule that triggers the left pointer to move, such as a sum exceeding a limit or a distinct character count breaking a threshold.
  • Choose the correct state tracker for the data type. Use a running integer for sums, a hash map for character frequencies, and an integer counter to track unique matches.
  • Memorise the basic expand-and-shrink loop structure. Remember that the right pointer steps unconditionally, the state updates immediately, and the left pointer uses a conditional loop to restore validity before evaluating the result.
Published by
Ansh Modi · Vrenic

Founder of Vrenic, the interview coach that grades every answer against a real rubric.

More from Vrenic