Interview conceptCoding & Algorithms

Two Pointers, Sliding Windows And Intervals

Asked of: Software Engineer

Last updated

What's being tested

These problems test recognizing when two pointers, sliding windows, or interval sweeps reduce a seemingly quadratic search to linear or near-linear time. You must maintain clear invariants while handling boundaries, duplicates, overlap, and invalid states. Strong solutions explain why pointer movement is safe and state time and space complexity precisely.

Patterns & templates

  • Opposing pointers for palindrome checks: compare left/right, and on one mismatch test both deletion branches; O(n) time, O(1) space.
  • Expanding/contracting sliding window for positive products: expand right, divide while product >= target, then add right - left + 1; O(n).
  • Monotonic reachability window for bounded jumps: track the furthest reachable zero and process newly available indices once; avoid rescanning ranges, targeting O(n).
  • Sort plus two pointers for triangle counting: fix the largest side, move left/right; if a[left] + a[right] > a[k], count right - left at once, O(n²).
  • Sort intervals and merge/sweep meeting ranges: merge when next.start <= current.end + 1 for inclusive dates; count uncovered days without expanding every day.
  • Preserve invariants explicitly: pointers only move forward, the window remains valid after contraction, and each element is inserted and removed at most once.
  • Guard edge cases: target <= 1, empty or singleton arrays, all-zero products, duplicate values, adjacent intervals, endpoint inclusivity, and integer overflow.

Common pitfalls

Pitfall: Applying product-window division when values can be zero or negative; split at zeros or use a different technique because monotonicity no longer holds.

Pitfall: Counting right - left + 1 before restoring the validity condition, or forgetting that inclusive intervals require merging touching ranges.

Pitfall: Claiming O(n) for a sorted two-pointer algorithm while ignoring the O(n log n) sort, or mutating input without stating that tradeoff.

Practice these

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

Practice questions

Related concepts