Codacoda
Back to Academy

patterns

Sliding Window

The sliding window technique maintains a subset (window) of elements as it moves across data, adding new elements at one end and removing from the other. It comes in two flavors: fixed-size windows for problems like maximum sum subarrays, and variable-size windows that expand or shrink based on a condition.

Use Cases

  • Finding the maximum sum subarray of size k
  • Longest substring without repeating characters
  • Minimum window substring containing all target characters

Complexity Analysis

MetricBestAverageWorst
TimeO(n)O(n)O(n)
SpaceO(k)

Visualization

215132012345
K:3
Speed:1x
Array: [2, 1, 5, 1, 3, 2]. Find max sum of subarray with size K=3.Step 1 / 6

Implementation

Output

Click "Run Code" to see output...