Interview conceptCoding & Algorithms

Sliding Window And Two Pointers

Asked of: Software Engineer

Last updated

A six-frame trace shows a sliding window expanding and shrinking to preserve a sum constraint, followed by sorted two pointers moving inward to find a target sum.

What's being tested

These problems test sliding-window and two-pointer reasoning: maintaining a valid contiguous range or exploiting sorted order without redundant work. You should demonstrate correct boundary movement, appropriate state structures, and O(n) time with O(1) or O(n) auxiliary space where applicable.

Patterns & templates

  • Fixed-size sliding window — initialize the first k elements, update by adding right and removing left; compute each result in O(n) time.
  • Variable-size window — expand right, then advance left while invalid; record the best valid window after restoring the invariant.
  • Last-seen index map — for repeated characters or values, jump left to max(left, last[value] + 1) so it never moves backward.
  • Monotonic deques — maintain decreasing maxima and increasing minima for limit-constrained windows; each element enters and leaves once, giving O(n) time.
  • Sorted two pointers — start at both ends; if the sum is too small move left, if too large move right, using O(1) extra space.
  • Window bounds — use inclusive indices consistently: length is right - left + 1; remove elements only when they leave the window.
  • Rounding and arithmetic — retain an exact running sum, then round each average at output time; handle fewer-than-window-size inputs explicitly.

Common pitfalls

Pitfall: Moving left directly to a stale duplicate index can move it backward; always use max(left, last_seen[value] + 1).

Pitfall: Removing from a deque or set without checking whether the outgoing index/value is still represented can corrupt window state.

Pitfall: Assuming two pointers works on an unsorted array; sorting changes original positions and may violate required index or constant-space constraints.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts