Lesson 186

Sliding Window

Fixed · Variable · Two Pointers

1:00

Slide a window of contiguous elements across an array or string, reusing the overlap to reduce O(n·k) or O(n²) brute force down to O(n).

By the end, you can

  • Explain why a sliding window achieves O(n) while a brute-force window scan costs O(n·k) or O(n²).
  • Implement the fixed-size sliding window for max sum of k consecutive elements, correctly computing the first window and updating with enter/leave.
  • Implement the variable-size sliding window for longest substring under a constraint, including zero-count key deletion.
  • Choose between a fixed and variable window given a problem statement.
  • Apply the `n - k + 1` formula to count fixed windows and the `right - left + 1` formula for window length.
  • Identify when sliding window does not apply (non-contiguous selections).
  • Analyze the amortized O(n) time and O(1)/O(k) space complexity of a sliding window solution.
Up next in Coding Interview Patterns
Questions or feedback?