How to Implement Sliding Window in Python

Vaibhhav Khetarpal Feb 02, 2024
How to Implement Sliding Window in Python

At any given point, any window that can be said to be a subset of a given particular data structure is known as a sliding window. The window size decides the number of elements that this subset would hold.

This tutorial discusses the sliding window and demonstrates how to implement it in Python.

The main reason for using a sliding window is that it reduces the time complexity. It specializes in solving the problems solved using the brute force method at an even faster rate.

A sliding window can be useful in simple coding tasks and humongous and advanced tasks like digital image processing and object detection. However, this article will focus on a simple area to help you understand the sliding window and how it is utilized.

To explain this better, we will take an example of a problem and then implement a sliding window on it. For this article, we take the following problem:

Given an array of numbers of size x. find a subarray of window size k having maximum sum.

Input: x =[12,11,10,23,55,45,15,28], k=3.

Now, we will apply a sliding window to solve this problem.

n = int(input("enter size of array "))
print("enter arrays elements")
a = list(map(int, input().split()))
k = int(input("enter the size of subarray "))
ms = -(10 ** 6)
ws = sum(a[:k])
for i in range(n - k):
    ms = max(ms, ws)
    ws = ws - a[i] + a[i + k]
ms = max(ms, ws)
print("subarray of size {} with maximum sum as {}".format(k, ms))

The above code provides the following output:

enter size of array 8
enter arrays elements
12 11 10 23 55 45 15 28
enter the size of subarray 3
subarray of size 3 with maximum sum as 123
Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

Related Article - Python Array