Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 5 of 20

Two pointers and sliding window

Two pointers means walking a sequence with two indices instead of one, often from both ends inward. A sliding window is a related idea: keep a running range [left, right] over the data and slide it instead of recomputing from scratch. Both turn an O(n²) nested loop into a single O(n) pass. A sliding window is really two pointers moving the same direction — one pattern, two shapes — which is why this section treats them together. Think of two clerks checking a sorted shelf of price tags from both ends to find a pair that adds up to a budget, meeting in the middle instead of one clerk comparing every tag to every other tag.

Pattern Naive With the pattern
pair summing to a target (sorted data) O(n²): check every pair O(n): two pointers from both ends
best/sum of every k-length window O(n·k): re-add k items each time O(n): add the new item, drop the old one
def two_sum_sorted(prices: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(prices) - 1
    while left < right:
        total = prices[left] + prices[right]
        if total == target:
            return prices[left], prices[right]
        if total < target:
            left += 1          # too small: drop the smallest, move inward
        else:
            right -= 1         # too big: drop the largest, move inward
    return None

prices = sorted([10, 60, 190, 250, 340])
print(two_sum_sorted(prices, 400))     # (60, 340)

A fixed-size sliding window keeps a running total instead of re-summing every window:

def best_k_day_sales(daily_sales: list[int], k: int) -> tuple[int, int]:
    window_total = sum(daily_sales[:k])
    best_total, best_start = window_total, 0
    for end in range(k, len(daily_sales)):
        window_total += daily_sales[end] - daily_sales[end - k]   # slide, don't re-sum
        start = end - k + 1
        if window_total > best_total:
            best_total, best_start = window_total, start
    return best_start, best_total

daily_sales = [1200, 900, 1500, 2100, 1800, 700, 2600, 2200]
print(best_k_day_sales(daily_sales, 3))    # (5, 5500): days 5-7 sell Rs 5,500

A variable-size window grows on the right and shrinks on the left whenever a rule is broken - for example, the longest run of days whose total rainfall stays under a limit (see the full program for the code: it is the same shrink-while-too-big shape as the window above, just with a while instead of a fixed k).

Real-world example: best_k_day_sales finds a shop's best 3-day sales stretch out of a week of daily numbers without re-adding the same days over and over - exactly what a sales dashboard's "best streak" widget needs.

Practice: pair-sum or pair-difference on sorted data; fixed-size window max/min/sum (best/worst k-day or k-item stretch); longest substring or subarray meeting a condition (variable-size window).

Practice on LeetCode - start here: Valid Palindrome · Best Time to Buy and Sell Stock · Maximum Average Subarray I · Two Sum II - Input Array Is Sorted · Longest Substring Without Repeating Characters · Container With Most Water

Show the full practice list (15 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Full program: examples/05_two_pointers_sliding_window.py.

Exercise 5: Two pointers — pair that hits a delivery weight limit

Scenario: A courier wants to combine exactly two parcels per trip so each trip's total weight is as close as possible to (but not over) a limit. What to do: Write best_pair_under_limit(weights: list[int], limit: int) -> tuple[int, int] | None. Sort the weights, then use two pointers from both ends: if the pair's sum is under the limit, remember it only if it beats the best pair found so far, then move the LEFT pointer right (try a heavier partner); if the sum is over the limit, move the RIGHT pointer left. Stop when the pointers meet. Print the best pair and its total for the data below.

Starting data:

WEIGHTS = [4, 8, 15, 7, 2, 11]
LIMIT = 18

Sample output:

Weights sorted: [2, 4, 7, 8, 11, 15]
Best pair under 18kg: (7, 11), total 18kg
Show the solution to Exercise 5
"""Exercise 5: Two pointers - best pair of parcels under a weight limit.

Run:   python ex03.py   (macOS/Linux: python3 ex03.py)
"""

WEIGHTS = [4, 8, 15, 7, 2, 11]
LIMIT = 18


def best_pair_under_limit(weights: list[int], limit: int) -> tuple[int, int] | None:
    ordered = sorted(weights)
    left, right = 0, len(ordered) - 1
    best: tuple[int, int] | None = None
    while left < right:
        total = ordered[left] + ordered[right]
        if total <= limit:
            if best is None or total > best[0] + best[1]:
                best = (ordered[left], ordered[right])
            left += 1
        else:
            right -= 1
    return best


def main() -> None:
    ordered = sorted(WEIGHTS)
    print("Weights sorted:", ordered)
    pair = best_pair_under_limit(WEIGHTS, LIMIT)
    print(f"Best pair under {LIMIT}kg: {pair}, total {pair[0] + pair[1]}kg")


if __name__ == "__main__":
    main()

💡 Hint: This is like two_sum_sorted in examples/05_two_pointers_sliding_window.py, but instead of stopping at an exact match, keep the best-so-far and keep scanning.

Search the guide