two-pointers sliding-window ⏱️ 9 min read • Updated 2026-10-19

Two Pointers vs Sliding Window

Opposite Ends Narrowing vs Monotonic Contiguous Windows

How to decide between inward-converging pointers on a sorted array and an expanding-contracting window on contiguous data.

⚡ The Discriminating Question

"Does expanding or shrinking the boundary change the validity condition monotonically, or are you pruning search space from opposite ends of a sorted array?"

Ask this single question during the first two minutes of reading the problem prompt. The answer decides your fundamental pattern.

💡In Plain Words: Sleeper Coach Ticket Examiners vs The Platform Window

Picture a passenger train coach window you slide along the platform. As you slide the window frame forward, passengers come into view on the right and slide out on the left. The window always frames a single contiguous slice of people standing together. Now picture two ticket examiners who board a sleeper coach at opposite doors (berth 1 at one end, berth 72 at the other). They walk inward toward each other down the central corridor. Every time they meet a passenger, they decide which examiner steps forward based on whose berth number needs checking next. They do not maintain a contiguous window. Instead, they eliminate entire sections of the coach with each step.

Key Takeaway: Use Sliding Window when your target is a contiguous subarray or substring whose validity moves in one predictable direction as you expand or shrink. Use Two Pointers when the data is sorted (or can be sorted) and comparing extremes lets you eliminate impossible candidate pairs without checking them.

When to Choose Which Pattern

Two Pointers (Inward or Converging)

Option A
Choose this when:
  • ✓The array is sorted, or sorting it in O(N log N) time is acceptable.
  • ✓You need to find a pair, triplet, or extreme boundary (such as maximum container area).
  • ✓Comparing the elements at left and right allows you to discard at least one index permanently.
  • ✓The target does not have to be a contiguous slice of the original unsorted array.
Time ComplexityO(N) after an optional O(N log N) sort
Auxiliary SpaceO(1) auxiliary space

Sliding Window (Expanding and Contracting)

Option B
Choose this when:
  • ✓The problem explicitly asks for a contiguous subarray or substring (e.g. longest, shortest, or sum equal to K).
  • ✓Values are non-negative or the condition behaves monotonically: growing the right boundary only moves the metric in one direction.
  • ✓When the condition is violated, advancing the left boundary restores validity.
  • ✓Both boundaries advance from left to right across the sequence.
Time ComplexityO(N) linear time because each pointer visits every element at most once
Auxiliary SpaceO(1) to O(K) space for frequency counters or hash sets

Side-by-Side Worked Examples

Compare concrete implementations side by side to see how the code structure diverges.

Container With Most Water(LC 11)

LeetCode ↗

Place left at index 0 and right at index n - 1. The container area is limited by min(height[left], height[right]) * (right - left). Moving the taller pointer inward can never increase the area because the width decreases while the height remains capped by the shorter bar. Therefore, advancing the shorter pointer is the only move that could discover a taller container.

Python 3LC 11
def maxArea(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    max_water = 0
    while left < right:
        width = right - left
        current_height = min(height[left], height[right])
        max_water = max(max_water, width * current_height)
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return max_water

Longest Substring Without Repeating Characters(LC 3)

LeetCode ↗

Expand the right pointer one character at a time, inserting characters into a frequency map. The moment any character count exceeds 1, the window is invalid. Increment left while evicting characters until the duplicate is dropped. Update the maximum window length at each valid state.

Python 3LC 3
def lengthOfLongestSubstring(s: str) -> int:
    seen = set()
    left = 0
    max_len = 0
    for right, ch in enumerate(s):
        while ch in seen:
            seen.remove(s[left])
            left += 1
        seen.add(ch)
        max_len = max(max_len, right - left + 1)
    return max_len

The Decision Matrix

Target Structure

Two Pointers (Inward or Converging)

Pairs, triplets, or extreme boundaries (often non-contiguous)

Sliding Window (Expanding and Contracting)

Contiguous subarray or substring

Data Ordering

Two Pointers (Inward or Converging)

Requires sorted data (or order invariance where sorting is allowed)

Sliding Window (Expanding and Contracting)

Operates on the original sequence order (sorting breaks contiguity)

Boundary Movement

Two Pointers (Inward or Converging)

Pointers move toward each other (inward) or at different speeds (fast/slow)

Sliding Window (Expanding and Contracting)

Both boundaries move in the same direction (left to right)

Monotonicity Requirement

Two Pointers (Inward or Converging)

Sorted comparison must safely discard one end without missed candidates

Sliding Window (Expanding and Contracting)

Expanding right must predictably push the metric in one direction

⚠️

Where Candidates Go Wrong (Top Traps)

✕

Using Sliding Window on arrays with negative numbers

Why it fails in interviews: If elements can be negative, expanding the window might decrease the sum, and shrinking might increase it. Monotonicity breaks completely, making it impossible to know which pointer to move.
✓The Senior Engineer Fix: When subarray sums involve negative numbers, abandon Sliding Window and use Prefix Sum with a Hash Map (LeetCode 560).
✕

Using an if statement instead of while when contracting the window

Why it fails in interviews: If adding one element causes multiple violations, a single left++ might leave the window in an illegal state.
✓The Senior Engineer Fix: Always use a while loop for shrinking: while window_is_invalid: remove(arr[left]); left += 1.
✕

Confusing subarray with subsequence

Why it fails in interviews: A subarray must be contiguous; a subsequence allows skipping elements. Sorting an array destroys contiguous subarrays.
✓The Senior Engineer Fix: If the problem asks for contiguous segments, never sort the array without realizing you broke the original contiguous order.

Related Walkthroughs in our DSA Course

Explore step-by-step solutions with 4-language code flaps (Java, C#, TS, Python) and visual memory dry runs.

problem

3Sum (Two Pointers on Sorted Array)

View in DSA Path→
problem

Longest Consecutive Sequence (Set vs Pointers)

View in DSA Path→
primer

Prefix Sum Pattern Primer

View in DSA Path→
⚖️What Did I Give Up By Choosing This? (The Tradeoff)

"Two Pointers requires sorted data (paying an O(N log N) sorting cost if the array is unsorted) and gives up contiguous subarray tracking. Sliding Window preserves original contiguous ordering and uses O(1) space, but strictly requires monotonic condition changes."

Practice Real Indian Hiring Loops

See the exact problems asked at Flipkart, Swiggy, Razorpay, PhonePe, and Amazon with verified candidate reports and round structures.