HOWTO · Python

How to Implement Sliding Window in Python

This tutorial discusses the sliding window technique and how to implement it in Python. Learn about its applications, advantages, and practical code examples to enhance your programming skills. Master this efficient method for solving array-related problems and elevate your coding abilities.

On this page

A sliding window keeps a contiguous range of items and moves that range through a list or string. In Python, this pattern is useful when each next answer can be updated from the previous window instead of recomputing all of its contents. The examples below show three common forms: a fixed-size window, a variable window with unique characters, and a window that meets a sum target.

What is the Sliding Window Technique?

A window is a range identified by left and right positions. It can have a fixed length, or its length can change as the algorithm adds or removes items. Because its elements stay contiguous, a sliding window fits tasks about subarrays and substrings; it does not directly describe arbitrary selections with gaps.

The technique often reduces repeated work. For example, after calculating one window’s sum, moving one position means subtracting the departing value and adding the arriving value. That update takes constant time. The total complexity depends on the particular algorithm and its data structure, so sliding window does not guarantee a speedup or O(n) time for every problem.

Implementing Sliding Window for Maximum Sum of Subarray of Size K

For a list of numbers and a positive window size k, first sum the initial k values. Then advance the window one position at a time, updating its sum with the outgoing and incoming values. Keep the largest sum seen. This example returns None if k is not positive or is larger than the list, making the input contract explicit.

The list [2, 1, 5, 1, 3, 2] with k = 3 has windows [2, 1, 5], [1, 5, 1], [5, 1, 3], and [1, 3, 2]. The program prints the greatest sum. It takes O(n) time and O(1) additional space, where n is the list length.

def max_sum_subarray(values, k):
    if k <= 0 or k > len(values):
        return None

    window_sum = sum(values[:k])
    best_sum = window_sum

    for right in range(k, len(values)):
        window_sum += values[right] - values[right - k]
        best_sum = max(best_sum, window_sum)

    return best_sum

values = [2, 1, 5, 1, 3, 2]
k = 3
print(max_sum_subarray(values, k))

This sample code is provided for you to run; no execution result is claimed here.

Sliding Window for Longest Substring Without Repeating Characters

For this task, the window contains no duplicate characters. Move the right position across the string and add each new character to a set. When the new character is already present, move the left position forward and remove those departing characters until the duplicate is gone. Update the longest length after restoring the condition.

Each position moves forward at most once, and each character enters and leaves the set at most once. The algorithm therefore takes O(n) time and O(min(n, alphabet size)) space for a string of length n. Python iterates through Unicode code points; a user-perceived grapheme, such as a base letter combined with a mark, may contain more than one code point.

def longest_unique_substring_length(text):
    window_chars = set()
    left = 0
    best_length = 0

    for right, char in enumerate(text):
        while char in window_chars:
            window_chars.remove(text[left])
            left += 1
        window_chars.add(char)
        best_length = max(best_length, right - left + 1)

    return best_length

text = "abcabcbb"
print(longest_unique_substring_length(text))

This sample code is provided for you to run; no execution result is claimed here.

Sliding Window for Minimum Size Subarray Sum

For a target sum, this approach finds the shortest contiguous subarray whose sum is at least the target. It relies on all values being nonnegative: when the running sum is large enough, removing a value from the left cannot make the sum larger, so shrinking the window can identify a shorter valid range. With negative values, that reasoning fails and a different algorithm is needed.

The function returns 0 when no qualifying subarray exists. With nonnegative values and a positive target, each position is added and removed at most once, giving O(n) time and O(1) additional space. The code accepts a nonpositive target as a zero-length answer, since no elements are needed to reach it.

def min_subarray_length(target, values):
    if target <= 0:
        return 0

    left = 0
    running_sum = 0
    shortest = len(values) + 1

    for right, value in enumerate(values):
        running_sum += value
        while running_sum >= target:
            shortest = min(shortest, right - left + 1)
            running_sum -= values[left]
            left += 1

    return 0 if shortest > len(values) else shortest

values = [2, 3, 1, 2, 4, 3]
target = 7
print(min_subarray_length(target, values))

This sample code is provided for you to run; no execution result is claimed here.

Conclusion

A sliding window is a useful way to reason about contiguous ranges in a list or string. Choose a fixed window when its size is known; adjust its boundaries when a condition such as unique characters or a target sum determines the range. Before using the pattern, check that the maintained state can be updated as the window moves and that the algorithm’s assumptions fit the input. These examples cover common Python interview problems, but other constraints may call for a different approach.

FAQ

  1. When should I use a sliding window? Use it when a problem concerns contiguous subarrays or substrings and the current result can be updated while moving one or both boundaries.
  2. Is every sliding-window algorithm O(n)? No. These examples are linear because their boundary movement and per-step updates are bounded. Other algorithms may perform more work per move.
  3. Can I use this minimum-sum window with negative numbers? Not as written. Its shrinking rule depends on nonnegative values; negative values can make the sum rise after removing an item.
  4. What is the difference between a subarray and a subsequence? A subarray is contiguous. A subsequence can skip positions while preserving order, so a window does not enumerate every subsequence.