Longest Substring Without Repeating Characters

mediumPython

Lesson

The Sliding Window Technique

The sliding window technique is a powerful algorithmic pattern used to solve problems involving contiguous subarrays or substrings. Instead of checking every possible substring (which would be O(n³) time complexity), we maintain a "window" that expands and contracts as we traverse the data structure.

The key insight is that we can reuse computations from previous windows. When we move the window, we don't start from scratch – we incrementally update our current state by adding new elements and removing old ones.

For substring problems without repeating characters, we use two pointers: a left pointer marking the window's start and a right pointer marking the end. We also maintain a data structure (like a hash set) to track what's currently in our window.

The algorithm works by:

  1. Expanding the right boundary to include new characters
  2. Checking if the new character creates a duplicate
  3. If there's a duplicate, contracting the left boundary until the duplicate is removed
  4. Tracking the maximum window size seen so far

This approach ensures we visit each character at most twice (once when adding, once when removing), giving us O(n) time complexity. The space complexity is O(min(m,n)) where m is the character set size, since our hash set can't grow larger than the unique characters in the string.

Sliding window is particularly effective for optimization problems on sequences where you need to find optimal contiguous subarrays or substrings.

Example
1def max_sum_subarray(arr, k): 2 """Find maximum sum of any subarray of length k using sliding window.""" 3 if len(arr) < k: 4 return 0 5 6 # Calculate sum of first window 7 window_sum = sum(arr[:k]) 8 max_sum = window_sum 9 10 # Slide the window: remove leftmost, add rightmost 11 for i in range(k, len(arr)): 12 window_sum = window_sum - arr[i - k] + arr[i] 13 max_sum = max(max_sum, window_sum) 14 15 return max_sum
L6Initialize window with first k elements - compute once rather than repeatedly
L10Slide window by removing left element and adding new right element
L11Update maximum without recalculating entire sum each time

Key Takeaways

  • •Sliding window reduces time complexity by reusing previous computations instead of starting fresh each time
  • •Use two pointers and a tracking data structure (set/map) to maintain window state efficiently
  • •The technique works best for contiguous sequence problems where you can incrementally update your solution
Loading...