jainvidhika410's blog

By jainvidhika410, history, 26 minutes ago, In English

Introduction

Sliding Window is a common technique in Competitive Programming used to solve problems involving contiguous subarrays or substrings efficiently.

Basic Idea

Instead of recalculating the answer for every subarray, maintain a window and update it while moving through the array.

Example

Array: 1 2 3 4 5

Window size = 3

First window: 1 + 2 + 3 = 6

Move window by one position: 2 + 3 + 4 = 9

Instead of recomputing from scratch:

new_sum = old_sum — outgoing_element + incoming_element

Complexity

Brute Force: O(n*k)

Sliding Window: O(n)

Sample Python Code

n, k = map(int, input().split()) a = list(map(int, input().split()))

cur = sum(a[:k]) best = cur

for i in range(k, n): cur += a[i] — a[i-k] best = max(best, cur)

print(best)

Common Problems

  1. Codeforces 363B — Fence
  2. Maximum Sum Subarray of Size K
  3. Longest Substring Without Repeating Characters
  4. Books (Codeforces 279B)

Conclusion ==========

Sliding Window is one of the first optimization techniques every competitive programmer should learn. It converts many O(n²) solutions into O(n) solutions and appears frequently in Codeforces contests.

  • Vote: I like it
  • 0
  • Vote: I do not like it