MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Sliding Window Algorithm: Fixed & Dynamic Window Strategies0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
2.1Static vs Dynamic Arrays, Amortized O(1) Operations & Memory Locality2.2Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns2.3Sliding Window Algorithm: Fixed & Dynamic Window Strategies2.4Prefix Sums & Difference Arrays for Constant-Time Range Queries
HomeTutorialsData Structures & AlgorithmsSliding Window Algorithm: Fixed & Dynamic Window Strategies
Prefix Sums & Difference Arrays for Constant-Time Range Queries

Sliding Window Algorithm: Fixed & Dynamic Window Strategies

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

The Sliding Window Algorithm is a sub-array and sub-string optimization technique. Instead of recalculating contiguous segments from scratch using nested loops ($O(n^2)$), the algorithm maintains a moving "window" that slides across the sequence, updating the internal state incrementally in $O(n)$ linear time.


1. Real-World Analogy: The Train Window

Imagine you are riding a train through the countryside, looking out through a small rectangular window:

  • As the train moves forward 1 meter, you do not need to rediscover the entire landscape.
  • One tree enters your field of view from the right, and one tree leaves your field of view from the left.
  • The remaining scenery inside the window stays identical! This is the essence of sliding window: Add incoming element on the right, subtract outgoing element on the left.

2. The Two Window Paradigms

Type 1: Fixed-Size Window ($K$)

The size of the window is strictly constant (e.g. "Find maximum sum of any contiguous subarray of length $K$").

  • Advance right pointer until window size equals $K$.
  • At each subsequent step: add arr[right], subtract arr[left], and increment both pointers (left++, right++).

Type 2: Dynamic (Variable-Size) Window

The window size expands and shrinks dynamically to satisfy a constraint (e.g. "Find the longest substring without repeating characters", "Smallest subarray with sum $\ge S$").

  • Expand right pointer to include elements and update state.
  • While the window constraint is violated, shrink the window from the left (left++) until valid again.
  • Record the maximum/minimum window length at valid states.

3. Fixed Window Implementation: Max Subarray Sum of Size $K$

Python 3:

1def max_sub_array_sum(nums: list[int], k: int) -> int:
2 if len(nums) < k:
3 return 0
4
5 # 1. Compute initial sum of first k elements
6 window_sum = sum(nums[:k])
7 max_sum = window_sum
8
9 # 2. Slide the window from index k to end
10 for right in range(k, len(nums)):
11 # Add new right element, subtract old left element (right - k)
12 window_sum += nums[right] - nums[right - k]
13 max_sum = max(max_sum, window_sum)
14
15 return max_sum

Modern JavaScript / TypeScript:

1export function maxSubArraySum(nums: number[], k: number): number {
2 if (nums.length < k) return 0;
3 
4 let windowSum = 0;
5 for (let i = 0; i < k; i++) {
6 windowSum += nums[i];
7 }
8 
9 let maxSum = windowSum;
10 for (let right = k; right < nums.length; right++) {
11 windowSum += nums[right] - nums[right - k];
12 maxSum = Math.max(maxSum, windowSum);
13 }
14 
15 return maxSum;
16}

4. Dynamic Window: Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without duplicate characters:

Python 3:

1def length_of_longest_substring(s: str) -> int:
2 char_index_map = {} # Tracks last seen index of each character
3 max_len = 0
4 left = 0
5
6 for right, char in enumerate(s):
7 # If character is already in window, jump left pointer past it!
8 if char in char_index_map and char_index_map[char] >= left:
9 left = char_index_map[char] + 1
10
11 char_index_map[char] = right
12 max_len = max(max_len, right - left + 1)
13
14 return max_len

5. Trace Table: s = "abcabcbb"

rightcharleftWindow SubstringActionmax_len
0'a'0"a"Map: {a:0}1
1'b'0"ab"Map: {a:0, b:1}2
2'c'0"abc"Map: {a:0, b:1, c:2}3
3'a'1"bca"Duplicate 'a' seen at 0 → left = 0 + 1 = 13
4'b'2"cab"Duplicate 'b' seen at 1 → left = 1 + 1 = 23
5'c'3"abc"Duplicate 'c' seen at 2 → left = 2 + 1 = 33
6'b'5"b"Duplicate 'b' seen at 4 → left = 4 + 1 = 53
7'b'7"b"Duplicate 'b' seen at 6 → left = 6 + 1 = 73

Result: Maximum length is 3 ("abc"), achieved in single-pass $O(n)$ time!


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
How does a Sliding Window reduce the time complexity of finding the maximum sum subarray of size $K$ from $O(n \times K)$ to $O(n)$?
Question 2
When solving "Longest Substring with At Most K Distinct Characters", when should the left pointer advance?
Question 3
What is the space complexity of the Sliding Window technique when applied to an array of numbers with a fixed size $K$?
Question 4
Which of the following problems is NOT suitable for the Sliding Window pattern?
Question 5
In a dynamic sliding window where both left and right pointers only move forward from 0 to $n$, why is the total time complexity $O(n)$ even if there is a while loop nested inside a for loop?

Next Lesson

Prefix Sums & Difference Arrays for Constant-Time Range Queries

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Two-Pointer Technique: Opposite-Direction & Fast-Slow PatternsPrefix Sums & Difference Arrays for Constant-Time Range Queries

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext