Coding Interview Questions

Sliding Window: Fixed and Variable Templates

When is sliding window the right tool? Show the template.

Why Interviewers Ask This

Interviewers love sliding window because it turns O(n²) brute force into O(n). Recognizing when to apply it is the skill.

How to Answer

  1. 1

    Use when: problem asks for a contiguous subarray/substring satisfying some property, and the property is monotonic under window expansion/contraction.

  2. 2

    Fixed window (size k): advance right, when window exceeds k advance left by 1. Maintain aggregate.

  3. 3

    Variable window: advance right unconditionally; while window invalid, advance left. Track best at valid windows.

  4. 4

    Maintain aggregates incrementally — counter dict, sum, max in deque — so each step is O(1) amortized.

  5. 5

    Classic problems: longest substring without repeat, min window substring, max sum subarray of size k, longest substring with at most k distinct.

Sample Answer

I reach for sliding window when the question is "longest/smallest/best contiguous X such that..." and expanding the window monotonically changes validity. Template: two pointers l and r. Fixed-size: r++ each step, l++ when r-l+1>k. Variable: r++ unconditionally, while (invalid) l++. For 'longest substring without repeat' I keep a char-count map, expand r and increment, while any count>1 I advance l and decrement. Answer updates when the window is valid. For 'min window substring' I track how many required chars are still missing, shrink whenever missing==0. The trick is defining 'valid' as a monotonic predicate — if it's not monotonic, sliding window won't work and you probably need DP or hash+count.

Pro Tips

  • Pair sliding window with a HashMap/counter for "distinct chars" style constraints.

  • Monotonic deque handles "max in window" in O(1) amortized — leetcode 239.

  • HireMe AI (即答侠) gives the two templates side-by-side with 6 worked examples — pattern recognition gets automatic.

Frequently Asked Questions

Sliding window vs two pointers?

Sliding window is a specific two-pointer flavor where both pointers only move forward. General two-pointer also includes opposite-end techniques (sorted-array sum).

Can the window shrink from both sides?

Almost never in classic sliding window — if it does, you probably need DP or a different structure.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free