# Sliding Window Pattern in DSA: A Beginner-Friendly Guide

When I first started solving array and string problems, **Sliding Window** was one of the patterns that felt confusing.

The code itself is usually short, but understanding **when to move the window, what to remove, and what to add** can be difficult at first.

This blog explains the Sliding Window technique from the basics with a simple example.

* * *

## What is Sliding Window?

Sliding Window is a technique used to solve problems involving **contiguous portions of an array or string**.

Instead of repeatedly calculating the same elements, we maintain a window and move it through the input.

For example, consider:

```python
nums = [1, 12, -5, -6, 50, 3]
```

If the window size is `4`, our windows are:

```text
[1, 12, -5, -6]
[12, -5, -6, 50]
[-5, -6, 50, 3]
```

The window moves one position at a time.

That is why it is called **Sliding Window**.

* * *

# Why Do We Need Sliding Window?

Let's say we want to find the maximum sum of any `k` consecutive elements.

For:

```python
nums = [1, 12, -5, -6, 50, 3]
k = 4
```

We could calculate every window from scratch:

```text
1 + 12 + (-5) + (-6) = 2

12 + (-5) + (-6) + 50 = 51

(-5) + (-6) + 50 + 3 = 42
```

This works, but we are repeatedly calculating elements that were already included in the previous window.

Sliding Window avoids this unnecessary work.

* * *

# The Main Idea

Look at the first window:

```text
[1, 12, -5, -6]  50  3
```

Its sum is:

```text
2
```

Now we slide the window one position to the right:

```text
1  [12, -5, -6, 50]  3
```

What changed?

*   `1` left the window.
    
*   `50` entered the window.
    

So instead of calculating the entire sum again:

```text
new sum = old sum - element leaving + element entering
```

Therefore:

```text
new sum = 2 - 1 + 50
        = 51
```

This simple idea is the heart of the **fixed-size Sliding Window** technique.

* * *

# Fixed-Size Sliding Window

The general pattern looks like this:

```python
window = sum(nums[:k])

for i in range(k, len(nums)):
    window = window - nums[i-k] + nums[i]
```

The important line is:

```python
window = window - nums[i-k] + nums[i]
```

It means:

```text
Remove the element that is leaving
+
Add the element that is entering
```

* * *

# Example: LeetCode 643

One beginner-friendly problem for learning Sliding Window is:

**Maximum Average Subarray I**

Given an integer array `nums` and an integer `k`, find the contiguous subarray of length `k` that has the maximum average.

For example:

```python
nums = [1, 12, -5, -6, 50, 3]
k = 4
```

The possible windows are:

```text
[1, 12, -5, -6]       → sum = 2
[12, -5, -6, 50]      → sum = 51
[-5, -6, 50, 3]       → sum = 42
```

The maximum sum is:

```text
51
```

Therefore, the maximum average is:

```text
51 / 4 = 12.75
```

* * *

# Python Solution

```python
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        tot = sum(nums[:k])

        avg = tot / k
        maximum = avg

        for i in range(k, len(nums)):
            tot = tot - nums[i-k] + nums[i]

            avg = tot / k
            maximum = max(maximum, avg)

        return maximum
```

Let's understand it step by step.

* * *

## Step 1: Calculate the First Window

```python
tot = sum(nums[:k])
```

If:

```python
nums = [1, 12, -5, -6, 50, 3]
k = 4
```

then:

```python
nums[:k]
```

gives:

```text
[1, 12, -5, -6]
```

So:

```text
tot = 2
```

* * *

## Step 2: Calculate the First Average

```python
avg = tot / k
```

Therefore:

```text
avg = 2 / 4
    = 0.5
```

We store this as our current maximum:

```python
maximum = avg
```

* * *

# Step 3: Slide the Window

Now we start from index `k`:

```python
for i in range(k, len(nums)):
```

Since `k = 4`, the first value of `i` is `4`.

The new element is:

```python
nums[i]
```

which is:

```python
nums[4] = 50
```

The element leaving the window is:

```python
nums[i-k]
```

Since:

```text
i = 4
k = 4
```

we get:

```text
i - k = 0
```

Therefore:

```python
nums[i-k] = nums[0] = 1
```

So:

```python
tot = tot - nums[i-k] + nums[i]
```

becomes:

```text
tot = 2 - 1 + 50
    = 51
```

Our window has now moved from:

```text
[1, 12, -5, -6]
```

to:

```text
[12, -5, -6, 50]
```

* * *

# Step 4: Update the Maximum

We calculate:

```python
avg = tot / k
```

Therefore:

```text
avg = 51 / 4
    = 12.75
```

Then:

```python
maximum = max(maximum, avg)
```

The maximum becomes:

```text
12.75
```

The same process continues until we reach the end of the array.

* * *

# The Pattern to Remember

For a fixed-size Sliding Window, remember these three steps:

### 1\. Calculate the first window

```python
window = sum(nums[:k])
```

### 2\. Slide the window

```python
window = window - nums[i-k] + nums[i]
```

### 3\. Update the answer

```python
answer = max(answer, window)
```

That's the basic pattern.

* * *

# Time Complexity

A brute-force approach may repeatedly calculate the sum of every window.

Sliding Window allows us to update the sum in constant time for each movement.

Therefore:

```text
Time Complexity: O(n)
Space Complexity: O(1)
```

where `n` is the number of elements in the array.

* * *

# How to Recognize a Sliding Window Problem

When reading a LeetCode problem, look for words such as:

*   contiguous
    
*   consecutive
    
*   substring
    
*   subarray
    
*   window
    
*   exactly `k` elements
    
*   at most `k` elements
    
*   longest/shortest substring
    
*   maximum/minimum sum of consecutive elements
    

For example:

> Find the maximum sum of `k` consecutive elements.

This should immediately make you think:

**Fixed-size Sliding Window.**

* * *

# Common Mistake

One common mistake is recalculating the entire window every time.

For example:

```python
for i in range(n-k+1):
    total = sum(nums[i:i+k])
```

This repeatedly calculates values that were already calculated.

Instead, calculate the first window once and then update it:

```python
window = window - element_leaving + element_entering
```

* * *

# Fixed vs Variable Sliding Window

There are two major types of Sliding Window.

### Fixed-size window

The window size stays the same.

Example:

```text
k = 4

[1, 2, 3, 4]
   ↓
[2, 3, 4, 5]
   ↓
[3, 4, 5, 6]
```

Problems such as **Maximum Average Subarray I** use this pattern.

### Variable-size window

The window size can grow and shrink depending on a condition.

For example:

```text
[ a b c d e ]
  ←──────→
```

The window may expand when the condition is valid and shrink when the condition is violated.

Variable-size Sliding Window is slightly more difficult, so it is better to learn fixed-size windows first.

* * *

# Practice Roadmap

If you're new to Sliding Window, don't immediately jump into difficult problems.

A good progression is:

1.  **LeetCode 643 — Maximum Average Subarray I**
    
2.  **LeetCode 1456 — Maximum Number of Vowels in a Substring of Given Length**
    
3.  **LeetCode 1343 — Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold**
    
4.  **LeetCode 1876 — Substrings of Size Three with Distinct Characters**
    
5.  **LeetCode 209 — Minimum Size Subarray Sum**
    
6.  **LeetCode 3 — Longest Substring Without Repeating Characters**
    
7.  **LeetCode 1004 — Max Consecutive Ones III**
    
8.  **LeetCode 424 — Longest Repeating Character Replacement**
    

The first four help build the fixed-size pattern.

The later problems introduce **variable-size windows**, which require a deeper understanding of when to expand and shrink the window.

* * *

# Final Takeaway

Sliding Window is not a completely different way of thinking about arrays.

It is mainly about **reusing information from the previous window instead of calculating everything again**.

The most important idea is:

```text
Remove what leaves.
Add what enters.
Move the window.
Update the answer.
```

Once this becomes familiar, many array and string problems that initially look complicated become much easier to recognize.

**Start small, understand the pattern, and then increase the difficulty.**
