const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Patterns

LeetCode Two Pointers Pattern: The Complete Guide to Two Pointers and Sliding Window

Master two of the most versatile interview patterns — when to use each and how to apply them

9 min read|

Two pointers solve 20+ common interview problems

Master the pattern once, apply it everywhere

Two of the Most Versatile Patterns in Coding Interviews

If you could only learn two leetcode patterns before your next coding interview, two pointers and sliding window would be strong candidates. Together, they cover a surprising breadth of problems: pair finding, subarray optimization, string manipulation, and more.

Both patterns share a key insight: rather than checking every possible combination of elements (O(n²) or worse), you can use strategically placed pointers that move in a coordinated way to reduce the search to a single linear pass.

In this guide you will learn the exact mental model for each pattern, see the classic problems that define each technique, understand when to reach for one over the other, and walk away with a practice strategy to make these patterns automatic.

What Is the Two Pointers Pattern?

The two pointers pattern places two index variables — typically called left and right — at different positions in an array or string, then moves them toward or away from each other based on a condition. Instead of a nested loop that checks every pair, the two pointers together scan the structure once, keeping the time complexity at O(n).

The classic mental model is a sorted array with one pointer at the start and one at the end. You evaluate the pair, then move whichever pointer will bring you closer to your target. Because the array is sorted, you always know whether to move left forward or right backward.

Two pointers is most natural on sorted arrays and linked lists, but variants appear in unsorted structures too — for example, fast and slow pointers for cycle detection in a linked list.

  • Opposite direction: left starts at 0, right starts at end, they converge — used for pair-sum problems
  • Same direction (fast/slow): both start at 0, fast moves ahead — used for cycle detection, finding midpoints
  • Partition style: one pointer tracks the boundary of a subarray while the other scans forward — used in Dutch National Flag problems
⚠️

Common Confusion

Two pointers and sliding window look similar — both use two indices — but they solve different types of problems. Two pointers finds pairs or partitions; sliding window finds optimal subarrays or substrings. Keep reading to see the key difference.

Classic Two Pointer Problems

Three problems define the two pointer pattern at different difficulty levels. Practicing all three builds the full mental model and prepares you for variations you will see in leetcode interview rounds.

Two Sum II — Input Array Is Sorted (#167) is the purest example. The array is already sorted, so you place left at index 0 and right at the last index. If the sum equals the target you are done. If it is too small you move left forward; if too large you move right backward. One pass, O(n) time, O(1) space.

3Sum (#15) extends the idea to triplets. Fix one element with an outer loop, then run two pointers on the remaining sorted subarray to find pairs that sum to the negative of the fixed element. Sorting first costs O(n log n) and the two-pointer scan costs O(n) per outer iteration, so total is O(n²) — far better than the O(n³) brute force.

Container With Most Water (#11) asks you to maximize the area between two vertical lines. Wider is better, but height is capped by the shorter line. Start with the widest possible container, then move the pointer on the shorter side inward — the only move that could possibly find a taller container.

  • #167 Two Sum II — Sorted array, find pair summing to target: O(n) time, O(1) space
  • #15 3Sum — Find all unique triplets summing to zero: O(n²) time after sorting
  • #11 Container With Most Water — Maximize area between two lines: O(n) time
  • #125 Valid Palindrome — Check if string reads the same forward and backward: O(n) time
  • #42 Trapping Rain Water — More advanced two pointer / prefix max combination

What Is the Sliding Window Pattern?

The sliding window pattern maintains a subarray (or substring) between two pointers — typically called left and right — that define the current window. Instead of recomputing the window from scratch on every step, you expand the right pointer to include new elements and contract the left pointer to shrink the window when a constraint is violated.

Think of it like a physical window you slide along an array. When the view inside the window meets your criteria (contains all required characters, sums to a target, has no duplicates), you record the answer. When it violates the criteria, you slide the left edge to the right until the window is valid again.

Sliding window is most powerful for problems that ask about contiguous subarrays or substrings with a constraint — maximum length, minimum length, exact count, or some character frequency condition.

  • Fixed-size window: window size k is given; slide by one each step — used for max sum of k elements
  • Variable-size expand/contract: grow right freely, shrink left when constraint is broken — most common variant
  • Frequency map window: use a hash map to track character counts inside the window — used for anagram and permutation problems
💡

The Sorted Array Trigger

When you see "sorted array" or "sorted input" in the problem statement, two pointers is almost always the right pattern. When you see "subarray" or "substring" with a constraint, reach for sliding window first.

Classic Sliding Window Problems

Longest Substring Without Repeating Characters (#3) is the entry point for sliding window. Expand right to add characters; when a duplicate appears in the window, advance left until the duplicate is gone. Track the maximum window size seen. A hash set or frequency map keeps the duplicate check at O(1), so the whole solution is O(n).

Minimum Window Substring (#76) is the most challenging standard sliding window problem. You need the smallest substring of s that contains every character of t. Use a frequency map to count what you still need, expand right to satisfy the requirement, then contract left as far as possible while still satisfying it, recording the minimum window at each valid state. Time complexity is O(|s| + |t|).

Both problems share the same expand-then-contract skeleton. Once you internalize that skeleton, most sliding window problems reduce to figuring out what constraint governs the contraction step.

  • #3 Longest Substring Without Repeating Characters — Variable window, no duplicate chars: O(n)
  • #76 Minimum Window Substring — Variable window, must contain all chars of t: O(n + m)
  • #567 Permutation in String — Fixed-size window with frequency map: O(n)
  • #424 Longest Repeating Character Replacement — Variable window with character swap budget: O(n)
  • #239 Sliding Window Maximum — Fixed window, max element using a deque: O(n)

Two Pointers vs Sliding Window: When to Use Which

Both patterns use two indices, so they are easy to conflate. The distinction comes down to what question the problem is asking and what structure you are operating on.

Reach for two pointers when the problem involves finding a specific pair or set of elements that satisfy a condition — especially on a sorted array. The pointers work by converging from opposite ends, eliminating large portions of the search space with each step.

Reach for sliding window when the problem involves optimizing a contiguous subarray or substring — finding the longest, shortest, or best window that satisfies some constraint. The window expands and contracts as a unit rather than converging from two sides.

When in doubt, ask: "Am I looking for elements at specific positions (pair/triplet)?" — that is two pointers. "Am I looking for the best contiguous range?" — that is sliding window.

  • Two pointers: sorted array + pair/triplet sum problems
  • Two pointers: fast/slow pointer for linked list cycle detection
  • Two pointers: in-place array manipulation and partitioning
  • Sliding window: longest/shortest substring with a character constraint
  • Sliding window: maximum sum subarray of variable length
  • Sliding window: problems with "at most k distinct" or "exactly k" phrasing

Practice Strategy: How to Make These Patterns Automatic

The goal is not to memorize specific solutions — it is to recognize the pattern instantly when you see a new problem. That recognition only comes from deliberate, repeated practice that forces you to retrieve the pattern rather than just read it.

Start with the pure examples: Two Sum II for two pointers, Longest Substring Without Repeating Characters for sliding window. Solve each from scratch, then write down in one sentence why you chose that pattern. That verbalization is the core of pattern internalization.

Once the basics are solid, practice the harder variants: 3Sum, Minimum Window Substring, Trapping Rain Water. These problems require you to combine the core pattern with additional data structures or an outer loop.

YeetCode flashcards are designed exactly for this kind of leetcode practice. Each card presents a problem prompt and asks you to identify the pattern before revealing the approach. Over time, spaced repetition surfaces the cards you find hardest most frequently, accelerating the pattern recognition that experienced candidates develop naturally.

A realistic timeline: with 30 minutes per day of focused leetcode practice, most engineers solidify both patterns within two weeks — ready to apply them confidently in a real leetcode interview setting.

💡

Pattern-First Drilling

When reviewing a solved problem, cover the code and try to state the pattern aloud: "This is a sliding window problem because I need the longest contiguous substring satisfying X constraint." That verbal recall is what makes the pattern stick under interview pressure.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now