Algorithmssliding window two pointer

Sliding Window Two Pointer (Dynamic Expansion and Shrinking)

TT
Testlaa Team
May 14, 20261 min read

Sliding window is a two-pointer pattern on one sequence: L and R chase each other with monotonicity (usually L never moves backward). Recognizing this unifies many solutions.

Why this shows up in the real world

Merge conflict resolution in text editors scans with two cursors; sliding window problems are the single-sequence cousin. Subtitle timing adjusts start/end pairs (two pointers) per caption block.

Core idea (explained for students)

Document invariants: “L is smallest index making window valid ending at R” vs “R is largest index keeping validity with fixed L.” Pick the formulation that matches your proof of correctness.

Try this in Python

def min_subarray_len(target: int, nums: list[int]) -> int:
    s, L, best = 0, 0, len(nums) + 1
    for R, x in enumerate(nums):
        s += x
        while s >= target:
            best = min(best, R - L + 1)
            s -= nums[L]
            L += 1
    return 0 if best > len(nums) else best


print(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))

Common mistakes

  • Moving both pointers backward without a plan—breaks amortized analysis.
  • Assuming monotonicity when the predicate is not monotone—need binary search on answer or different structure.

Key takeaways

  • Same code shape as many two-pointer substring problems.
  • Prove why L only increments—this is the heart of O(n) time.

Tags:

Sliding windowPythonStudents