← DSA roadmap

Topic 10 of 21 · Intermediate

Two Pointers & Sliding Window

Turn O(n²) subarray/substring scans into O(n) by moving two indices smartly.

Concept

Two pointers: keep one index at each end (or both at the start) and move whichever pointer brings you closer to the answer. Works great on sorted arrays.

Sliding window: keep a window [left, right] that satisfies a condition. Grow right every step; shrink left while the window is invalid. Each element enters and leaves once, so total work is O(n).

Fixed-size windows (size k) just slide by one; variable windows expand and shrink based on a rule such as 'no repeated characters' or 'sum ≤ target'.

Complexity

OperationTimeSpace
Pair sum in sorted arrayO(n)O(1)
Longest substring without repeatsO(n)O(k)
Max sum of window size kO(n)O(1)

Code (Python)

def longest_unique_substring(s):
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1      # shrink past the duplicate
        last[ch] = right
        best = max(best, right - left + 1)
    return best

def min_subarray_len(target, nums):
    left = total = 0
    best = float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:       # window valid -> try shrinking
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

Remember

  • Ask: 'contiguous subarray/substring?' → think sliding window.
  • Sorted input + pair/triplet → think two pointers.
  • Each pointer only moves forward, which is why it's linear.

Practice these interview problems

  • 3Sum
  • Container With Most Water
  • Minimum Window Substring
  • Longest Repeating Character Replacement
Practice with the AI mentor

Lesson test

Take an 8-question test on “Two Pointers & Sliding Window” — concepts, output prediction, bug spotting and interview questions.