Topics/Strings/Sliding Window

Pattern

Sliding Window

Grow and shrink a contiguous segment [L, R] while tracking a constraint (sum, distinct count, validity) so every element enters and leaves the window at most once.

StringsFundamentalsPattern

When to use it

Longest/shortest substring with a property, fixed-size max/min, “at most K distinct”, anagrams in a string.

How it works

  1. Expand R and update the window state (sum, map, counter).
  2. While the window is invalid, advance L and undo state.
  3. Record the answer whenever the window is valid (or after each fixed-size step).
  4. Continue until R reaches the end.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionSliding Window

Why interviewers care

Gives O(n) solutions for substring/subarray problems that look like they need O(n²).

Drill Sliding Window with Strings problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Updating the map after moving L incorrectly
  • !Using < vs ≤ for “at most K”
  • !Forgetting to update the best answer every valid step
Loading visualization…

Practice this

Related Strings problems — open any one and apply Sliding Window.

Search bank →

More under Strings

← Back to Strings lesson