Two pointers are useful when a sequence’s structure lets two coordinated indices rule out work, build an output safely, or track a changing contiguous range. The technique is a family of patterns—not one template. Choose the pattern from the problem’s input properties and output requirements, then state the invariant that makes every pointer move safe.
What the two-pointer technique means
A two-pointer method uses two indices or references to inspect or manage positions in a sequence in a coordinated way. They might start at opposite ends and move inward, travel in the same direction at different speeds, or mark the boundaries of a window. The arrangement alone does not prove an algorithm correct: the input property and the invariant maintained by each move do that.
Choose a pattern from the problem’s structure
| Problem cue | Candidate pattern | Property to verify | Typical task |
|---|---|---|---|
| Sorted sequence and a pair or target condition | Opposite ends | Order makes one side safely discardable after each comparison | Pair sum or related search |
| In-place filtering or compaction | Same-direction read/write | The retained prefix is correct, and writes do not overwrite unread input | Remove duplicates |
| Contiguous substring or subarray with a changing constraint | Sliding window | The expand/shrink rules correctly maintain the constraint | Range or substring conditions |
| Mirrored comparisons or reversal | Opposite ends | Matching or swapping is symmetric | Palindrome check or sequence reversal |
These are common cues, not an exhaustive classification. In particular, sliding window is closely related to two pointers: its two indices delimit a contiguous interval, while the window’s summary and validity rules guide movement.
Opposite ends: search a sorted sequence
Pair sum and the elimination invariant
For a sorted array and target, initialize left at the first element and right at the last. The invariant is that any candidate pair discarded so far cannot equal the target. If the current sum is too small, every pair using the current left value and an index at or before right is also too small: the other value cannot be larger than the value at right. Advance left. If the sum is too large, every pair using the current right value and an index at or after left is also too large, so move right backward.
#1 Best Overall
When the sum matches, return or record the pair according to the task. If no match is found, stop once the pointers meet or cross; there is no pair of distinct remaining positions to test. This reasoning depends on sorted order or another proven monotonic property. Without it, a low sum does not establish that moving the left pointer is safe.
Sorting and output requirements
If the input is not sorted, sorting may make the scan possible, but it adds preprocessing cost and can change the problem. If the answer must include original indices or preserve input order, retain index information or choose a different approach that meets that requirement. Count sorting separately from the pointer scan rather than describing the whole solution as linear.
Rank #2
- Used Book in Good Condition
Same direction: read and write to compact in place
Maintain a correct output prefix
For duplicate removal from a sorted array, let a read pointer visit each item and a write pointer identify where the next retained value belongs. Maintain this invariant: positions before the write pointer contain exactly the unique values encountered so far, in order. When the value at the read pointer differs from the last retained value, write it at the next output position and advance the write pointer. Repeated values need not be copied into the retained prefix.
The result is a valid prefix of the original array. Return or report its length; values after that prefix are leftover storage and are not part of the compacted result unless the problem says otherwise. The writes are safe because the write position never runs ahead of the read position, so it does not overwrite an item that has not yet been visited.
Rank #3
This pattern can avoid a separate output array, but the invariant must match the task. For another filter, specify what the prefix contains and why each write preserves unread input.
Sliding window: track a contiguous range
Expand, update, and shrink deliberately
Use a window when the answer concerns a contiguous substring or subarray and a constraint can be tracked as the range changes. One endpoint typically expands the range; the other moves to restore validity or reduce the range. Update the needed summary—such as a sum or frequency counts—when elements enter or leave. Record a candidate answer at the point required by the problem, such as when the window is valid or after it has been reduced as far as the rule permits.
Do not apply a stock expand/shrink loop unless its rule is justified. For example, a sum-based window often relies on nonnegative values: adding an element cannot reduce the sum, which supports a particular monotonic adjustment. If values may be negative, that logic can fail; use an algorithm with an invariant that holds for the actual input.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.A step-by-step routine for solving a problem
- Define the output. Is the task asking for a pair, a transformed prefix, a contiguous range, or a yes/no result?
- Find the enabling property. Look for sorted order, contiguity, symmetry, or a safe in-place output prefix.
- Choose pointer placement. Decide whether indices should move inward, proceed in the same direction, or delimit a window.
- Write the invariant before coding. State what is known about discarded candidates, processed positions, retained values, or the current window.
- Justify every branch. Explain why each move preserves the invariant and cannot skip a valid answer.
- Check boundaries. Consider empty and one-element inputs, pointer meeting or crossing, duplicates, and the order of updates.
- Count the work. If each pointer only advances or moves inward and never resets, the scan takes linear time in the sequence length. Add sorting and auxiliary-data-structure costs separately.
How sliding window and two pointers relate
“Two pointers” describes the broad idea of coordinating two positions; a sliding window is a more specific use in which those positions delimit a contiguous range. A sorted pair-sum scan and an in-place read/write pass also use two pointers, but neither maintains a window. Choose by asking what the two indices represent and what invariant governs their movement—not by treating the names as interchangeable templates.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsQuick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




