Skip to content
Essay · Craft

What is the difference between sliding window and two pointers

The difference between sliding window and two pointers is what the pointers represent: a sliding window summarises a contiguous range, while two pointers discard candidate pairs. Here is how to tell them apart, with traces, operation counts and a counterexample.

By Vishy9 min readPublished · 1 Nov 2026

The difference between sliding window and two pointers is what the pointers mean. In a sliding window, both pointers bound a contiguous range whose contents you summarise. In two pointers, each pointer is an independent candidate position, and you move them using an ordering argument that discards possibilities. One tracks a region; the other prunes pairs.

Most tutorials blur these together because the code looks alike: two integers, a loop, some increments. That is a bad reason to treat them as one idea. They are justified by different arguments, they fail on different inputs, and picking the wrong one produces a solution that passes the samples and quietly returns wrong answers. I want to separate them cleanly, trace both on small numbers, and then show the exact input that breaks the window.

What does each pointer mean in a sliding window?

In a sliding window, the two pointers are the two edges of one contiguous range, and the range itself is the object you reason about. You do not care about the pointers as positions. You care about what is inside: its sum, the count of each character, the set of values it holds.

The mechanics follow from that. The right edge moves forward and adds one element to the summary. If the window now violates some rule, the left edge moves forward and removes elements until the rule holds again. After each step the window is valid, and you record whatever you are optimising, usually its length.

The cost argument is short. The right edge moves at most n times and the left edge moves at most n times, because neither ever goes backward. That is at most 2n pointer moves, and if adding and removing an element from the summary is O(1), the whole scan is O(n). Notice the condition. The technique only works when the summary supports removal cheaply. A running sum does. A count table does. A running maximum does not, because when the maximum leaves the window you do not know the next one without a monotonic deque or a heap. People forget this, and then their window quietly becomes O(n log n) or O(n^2).

Here is the shape for the problem of finding the longest run of positive numbers whose sum stays at or below a limit:

def longest_at_most(nums, s):
    left = total = best = 0
    for right, x in enumerate(nums):
        total += x
        while total > s:
            total -= nums[left]
            left += 1
        best = max(best, right - left + 1)
    return best

The variable that matters is total, the summary. The indexes are bookkeeping. If you want the full treatment of when the contraction loop is a while versus an if, the page on the sliding window pattern covers it.

What does each pointer mean in two pointers?

In converging two pointers, each pointer is a candidate position for one member of an answer, and you hold no summary of what lies between them. The elements in the middle are simply unexamined. All the state is two indexes and the two values under them.

My framing for this is locked doors. Imagine a corridor of rooms with a person at each end. Every step you take, you lock a door behind you for good, and the whole technique is a proof that the room you just locked could not have contained the answer. If you cannot state that proof in one sentence, you do not have a two-pointer solution yet; you have a hunch.

Take a sorted array and a target pair sum. With lo at the left end and hi at the right end, compute the sum. If it is too big, the value at hi is too big for every partner still available, because the smallest remaining partner is at lo and even that overshoots. So hi can never be part of an answer, and you lock that door by moving hi inward. If the sum is too small, the symmetric argument locks lo.

def pair_sum(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        t = nums[lo] + nums[hi]
        if t == target:
            return lo, hi
        if t < target:
            lo += 1
        else:
            hi -= 1
    return None

The same locked-door argument drives Container With Most Water: you move the shorter wall, because with the width already shrinking, only a taller wall could possibly beat the current area. The formal version of this reasoning lives in the converging pointers proof.

How do the two techniques behave on real numbers?

Both turn a quadratic search into a linear scan, but they do it by eliminating different things: the window eliminates recomputation, the pointers eliminate pairs. A trace on small inputs makes this concrete.

First the window. Take the array 3, 1, 2, 7, 4, 2, 1, 1, 5 and a limit of 8. I want the longest contiguous run with sum at most 8.

  • Right edge reaches index 2: window 3, 1, 2 has sum 6, length 3.
  • Index 3 adds 7, sum 13. Shrink: drop 3 (sum 10), drop 1 (sum 9), drop 2 (sum 7). Window is just 7, length 1.
  • Index 4 adds 4, sum 11. Drop 7, sum 4. Window is 4.
  • Indexes 5, 6, 7 add 2, 1, 1. Sum climbs to 6, 7, 8. The window 4, 2, 1, 1 has length 4, which is the best.
  • Index 8 adds 5, sum 13. Drop 4 (sum 9), drop 2 (sum 7). Window is 1, 1, 5, length 3.

The right edge moved 9 times and the left edge moved 6 times, 15 moves in total. Enumerating every subarray would cost 9 x 10 / 2 = 45 start-end pairs, and each would need a sum, so the saving here is modest because n is tiny.

Now the pointers. Sorted array 1, 3, 4, 6, 8, 11, 15 and a target of 14. Start with lo at 1 and hi at 15: sum 16, too big, so lock 15, because even 1 + 15 overshoots. Now 1 + 11 = 12, too small, so lock 1, because even the largest remaining partner, 11, falls short. Now 3 + 11 = 14. Found in 3 steps, against 21 pairs for brute force.

Scale it up and the picture sharpens. At n = 100,000, the number of pairs is about 5 x 10^9, and the number of subarrays is the same order. At roughly 10^8 to 10^9 simple operations per second in a compiled language, brute force runs for several seconds to a minute, and in Python it runs for far longer than any judge will wait. The two-pointer pair search does at most 99,999 steps. The window does at most 200,000 pointer moves. Both finish in a few milliseconds even in an interpreted language. The point is not the exact figure but the ratio: five orders of magnitude.

Why is the correctness argument different?

Both techniques rest on a never-go-back argument, but the thing that cannot go back is different. For the window it is the left edge, justified by monotonicity of a property of the range. For converging pointers it is each pointer, justified by an exchange or elimination argument about pairs.

Look at the window argument for the positive-sum problem. If the window from left to right has sum above the limit, then every longer window starting at left also exceeds it, because adding positive numbers only raises the sum. So left can be abandoned permanently for all future right edges. That is monotonicity: growing the range moves a quantity in one direction only.

The pointer argument does not mention ranges at all. It says that, given the sort order, a specific element cannot pair with anything still alive. This depends on order, not on contiguity. You could scatter the elements of a sorted array into a different data structure and the argument would survive, as long as you can reach the two extremes.

This explains the failure modes. A window needs a monotone property; it breaks when the data lets the property go backward. Converging pointers need a ordering that makes each discard safe; they break on unsorted input, where nothing licenses locking a door.

How do you decide which technique a problem needs?

Ask what the answer is made of. If it is a contiguous substring or subarray, reach for a window. If it is a pair or triple of positions chosen by a relationship between their values, in sorted or symmetric data, reach for pointers.

I run three questions in this order:

  1. Is the answer a contiguous range? If yes, you probably want a window, and the next question is whether the range property is monotone.
  2. Is the answer a tuple of positions related by sum, difference, or a product with width? If yes, look for sorted order or a symmetry that allows elimination.
  3. Do both pointers move the same direction, with one reading and one writing? Then it is neither: it is a reader and writer pair, as in removing duplicates in place or partitioning.

The table collects the differences.

AspectSliding windowConverging two pointersReader and writer pointers
What the pointers meanEdges of one contiguous rangeTwo independent candidatesRead position and write position
State keptSummary of the range (sum, counts, set)Just the two valuesJust the two indexes
DirectionBoth move rightMove toward each otherBoth move right, at different speeds
Total movesAt most 2nAt most nAt most 2n
Why it is correctMonotone property of the rangeOrdering argument discards a candidateInvariant on the written prefix
Breaks whenNegative values or non-monotone ruleInput is not sorted or symmetricOrder of kept elements matters and is violated
Typical problemsLongest substring without repeating3Sum (inner loop)Remove duplicates, move zeros

Hybrids exist and are worth noticing. 3Sum fixes one index, then runs converging pointers on the rest, so it is an outer loop with an inner two-pointer scan, O(n^2) overall after an O(n log n) sort. Minimum window substring is a window whose summary is a count table plus a number of satisfied characters. Neither is a new technique; each is a composition. If you want a wider view of the family, the two pointers topic page groups the problems.

What happens when negative numbers break the window?

With negative numbers, a sliding window can discard a left edge that was still needed, and it returns a wrong answer without any error. The monotonicity that justified the contraction no longer holds.

Here is the smallest counterexample I know. Find the longest contiguous run with sum at most 2 in the array 3, -2, 1. The true answer is 3, since the whole array sums to 2. Run the window: the right edge takes 3, sum 3 exceeds 2, so the left edge drops 3 and the window is empty. Then -2 enters, sum -2, length 1. Then 1 enters, sum -1, length 2. The window reports 2. It threw away the 3 because it assumed that any longer window starting there would also be too heavy, and the negative number that followed proved the assumption false.

The fix is a different tool. For exact-sum questions on arrays with negatives, store prefix sums and look up earlier ones in a hash map. The sum of a run from i to j is prefix[j] minus prefix[i], so asking for a run with sum k becomes asking whether prefix[j] - k has been seen before, which is O(n) time and O(n) space. The prefix sums concept explains the construction, and Subarray Sum Equals K is the standard exercise where the window fails and the map succeeds. You pay memory to buy back the correctness that monotonicity used to give for free.

I find this the most useful single test in practice. Before writing a window, ask whether adding one more element can ever make a violated rule become satisfied. If yes, the window is unsafe. For a sum with positives, no. For a sum with negatives, yes. For distinct-character rules, no, because extending the range can only add duplicates. That one question separates the safe uses from the traps.

Frequently asked questions

Is a sliding window just a kind of two pointers?

Mechanically yes, since a window is two indexes moving in the same direction. Conceptually no, because a window carries a summary of the range between them and relies on a monotone property, while converging pointers carry nothing and rely on order. Treating them as one idea is how people end up applying the wrong correctness argument.

Do I have to sort the array before using two pointers?

For converging pointers on a pair-sum question, yes, because the discard argument depends on order. Sorting costs O(n log n), which is usually fine, but it loses the original indexes, so if the problem asks for positions you must sort pairs of value and index, or use a hash map instead. Same-direction reader and writer pointers do not need sorting.

Can a sliding window work on an unsorted array?

Yes, sorting is irrelevant to a window. What it needs is a range property that moves one way as the range grows, such as a sum over positive values or a count of distinct characters. Order of the values is not the issue, but sign and monotonicity are.

Pick one problem where the two ideas meet and trace it by hand before touching code: start with Container With Most Water, write down the sentence that justifies each pointer move, and only then implement it.