Pattern 02 of 22

Two Pointers Pattern: Template + 201 LeetCode Problems

Use the order already in the input to discard half the search space at every step.

Easy
58
Medium
118
Hard
25

What the two pointers pattern is

Two pointers walk the input with two indices whose movement is driven by a comparison rather than by a loop counter, and the whole technique rests on one idea: if the input is ordered, the comparison tells you which pointer cannot possibly be part of the answer, so moving it throws away a whole family of candidates at once. In the converging form the pointers start at opposite ends and step inward — for a target sum, a total that is too small can only be fixed by a larger left value, so the left pointer moves and every pair involving the old left value is eliminated in one step. The same-direction form uses a slow write index behind a fast read index and is how in-place filtering and de-duplication are done without extra memory. The fast-and-slow variant advances one pointer twice as fast as the other, which detects a cycle in a linked list and finds its midpoint without knowing the length.

When to use it

  • The input is sorted, or sorting it first does not destroy the answer.
  • You are looking for a pair, triple, or a partition point rather than a subarray.
  • The problem asks for an in-place rewrite in O(1) extra space.
  • A linked list needs a midpoint, a cycle check, or the nth node from the end in one pass.

The two pointers template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 201 problems listed below.

PythonTwo Pointers template
def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1

    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return [left, right]
        if total < target:
            left += 1      # only a larger left value can reach the target
        else:
            right -= 1     # only a smaller right value can
    return []

Complexity characteristics

Time
O(n), or O(n log n) when the input has to be sorted first
Auxiliary space
O(1)

Each pointer only ever moves in one direction, so between them they take at most n steps and the scan is linear. When the input arrives unsorted the sort dominates and the whole solution is O(n log n) — worth saying out loud, because it is exactly the difference between this and a hash-map solution that stays linear. The extra space is two integers, and the fast-and-slow variant on a linked list is likewise O(1), which is normally the constraint being tested.

Eyes only

Meet the two pointers problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 201 two pointers LeetCode problems

Every problem in the library the two pointers pattern applies to, grouped by LeetCode's own difficulty rating. 169 of the 201 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (58)

Easy problems
No.Problem
0026Remove Duplicates from Sorted Array
0027Remove Element
0028Find the Index of the First Occurrence in a String
0088Merge Sorted Array
0125Valid Palindrome
0141Linked List Cycle
0160Intersection of Two Linked Lists
0202Happy Number
0234Palindrome Linked List
0283Move Zeroes
0344Reverse String
0345Reverse Vowels of a String
0349Intersection of Two Arrays
0350Intersection of Two Arrays II
0392Is Subsequence
0455Assign Cookies
0541Reverse String II
0557Reverse Words in a String III
0653Two Sum IV - Input is a BST
0680Valid Palindrome II
0696Count Binary Substrings
0876Middle of the Linked List
1768Merge Strings Alternately
0170Two Sum III - Data structure designPremium
0246Strobogrammatic NumberPremium
0408Valid Word AbbreviationPremium
0821Shortest Distance to a Character
0832Flipping an Image
0844Backspace String Compare
0905Sort Array By Parity
0917Reverse Only Letters
0922Sort Array By Parity II
0925Long Pressed Name
0942DI String Match
0977Squares of a Sorted Array
1089Duplicate Zeros
1099Two Sum Less Than KPremium
1332Remove Palindromic Subsequences
1346Check If N and Its Double Exist
1385Find the Distance Value Between Two Arrays
1455Check If a Word Occurs As a Prefix of Any Word in a Sentence
1826Faulty SensorPremium
1961Check If String Is a Prefix of Array
2000Reverse Prefix of Word
2108Find First Palindromic String in the Array
2200Find All K-Distant Indices in an Array
2367Number of Arithmetic Triplets
2441Largest Positive Integer That Exists With Its Negative
2460Apply Operations to an Array
2465Number of Distinct Averages
2511Maximum Enemy Forts That Can Be Captured
2540Minimum Common Value
2562Find the Array Concatenation Value
2570Merge Two 2D Arrays by Summing Values
2697Lexicographically Smallest Palindrome
2824Count Pairs Whose Sum is Less than Target
2903Find Indices With Index and Value Difference I
2970Count the Number of Incremovable Subarrays I

Medium (118)

Medium problems
No.Problem
0005Longest Palindromic Substring
0011Container With Most Water
00153Sum
00163Sum Closest
00184Sum
0019Remove Nth Node From End of List
0031Next Permutation
0061Rotate List
0075Sort Colors
0080Remove Duplicates from Sorted Array II
0082Remove Duplicates from Sorted List II
0086Partition List
0142Linked List Cycle II
0143Reorder List
0148Sort List
0151Reverse Words in a String
0165Compare Version Numbers
0167Two Sum II - Input Array Is Sorted
0189Rotate Array
0287Find the Duplicate Number
0443String Compression
0457Circular Array Loop
0475Heaters
0481Magical String
0522Longest Uncommon Subsequence II
0524Longest Word in Dictionary through Deleting
0532K-diff Pairs in an Array
0556Next Greater Element III
0567Permutation in String
0581Shortest Unsorted Continuous Subarray
0611Valid Triangle Number
0633Sum of Square Numbers
0647Palindromic Substrings
0658Find K Closest Elements
0763Partition Labels
1679Max Number of K-Sum Pairs
2095Delete the Middle Node of a Linked List
2130Maximum Twin Sum of a Linked List
2300Successful Pairs of Spells and Potions
2462Total Cost to Hire K Workers
0161One Edit DistancePremium
0186Reverse Words in a String IIPremium
0244Shortest Word Distance IIPremium
0251Flatten 2D VectorPremium
0253Meeting Rooms IIPremium
02593Sum SmallerPremium
0277Find the CelebrityPremium
0360Sort Transformed ArrayPremium
0723Candy CrushPremium
0777Swap Adjacent in LR String
0786K-th Smallest Prime Fraction
0795Number of Subarrays with Bounded Maximum
0809Expressive Words
0825Friends Of Appropriate Ages
0826Most Profit Assigning Work
0838Push Dominoes
0845Longest Mountain in Array
0870Advantage Shuffle
0881Boats to Save People
09233Sum With Multiplicity
0948Bag of Tokens
0962Maximum Width Ramp
0969Pancake Sorting
0986Interval List Intersections
1023Camelcase Matching
1048Longest String Chain
1055Shortest Way to Form StringPremium
1214Two Sum BSTsPremium
1229Meeting SchedulerPremium
1237Find Positive Integer Solution for a Given Equation
1265Print Immutable Linked List in ReversePremium
1471The k Strongest Values in an Array
1498Number of Subsequences That Satisfy the Given Sum Condition
1508Range Sum of Sorted Subarray Sums
1570Dot Product of Two Sparse VectorsPremium
1574Shortest Subarray to be Removed to Make Array Sorted
1577Number of Ways Where Square of Number Is Equal to Product of Two Numbers
1616Split Two Strings to Make Palindrome
1634Add Two Polynomials Represented as Linked ListsPremium
1650Lowest Common Ancestor of a Binary Tree IIIPremium
1712Ways to Split Array Into Three Subarrays
1721Swapping Nodes in a Linked List
1750Minimum Length of String After Deleting Similar Ends
1754Largest Merge Of Two Strings
1764Form Array by Concatenating Subarrays of Another Array
1813Sentence Similarity III
1850Minimum Adjacent Swaps to Reach the Kth Smallest Number
1855Maximum Distance Between a Pair of Values
1861Rotating the Box
1868Product of Two Run-Length Encoded ArraysPremium
1877Minimize Maximum Pair Sum in Array
1885Count Pairs in Two ArraysPremium
1898Maximum Number of Removable Characters
1963Minimum Number of Swaps to Make the String Balanced
2046Sort Linked List Already Sorted Using Absolute ValuesPremium
2105Watering Plants II
2109Adding Spaces to a String
2110Number of Smooth Descent Periods of a Stock
2149Rearrange Array Elements by Sign
2161Partition Array According to Given Pivot
2330Valid Palindrome IVPremium
2332The Latest Time to Catch a Bus
2337Move Pieces to Obtain a String
2396Strictly Palindromic Number
2406Divide Intervals Into Minimum Number of Groups
2410Maximum Matching of Players With Trainers
2422Merge Operations to Turn Array Into a PalindromePremium
2486Append Characters to String to Make Subsequence
2491Divide Players Into Teams of Equal Skill
2563Count the Number of Fair Pairs
2576Find the Maximum Number of Marked Indices
2592Maximize Greatness of an Array
2674Split a Circular Linked ListPremium
2825Make String a Subsequence Using Cyclic Increments
2838Maximum Coins Heroes Can CollectPremium
2856Minimum Array Length After Pair Removals
2905Find Indices With Index and Value Difference II
2938Separate Black and White Balls

Hard (25)

Hard problems
No.Problem
0042Trapping Rain Water
0295Find Median from Data Stream
0321Create Maximum Number
0719Find K-th Smallest Pair Distance
0272Closest Binary Search Tree Value IIPremium
1147Longest Chunked Palindrome Decomposition
1163Last Substring in Lexicographical Order
1537Get the Maximum Score
1697Checking Existence of Edge Length Limited Paths
1755Closest Subsequence Sum
1782Count Pairs Of Nodes
1793Maximum Score of a Good Subarray
1842Next Palindrome Using Same DigitsPremium
2035Partition Array Into Two Arrays to Minimize Sum Difference
2071Maximum Number of Tasks You Can Assign
2122Recover the Original Array
2193Minimum Number of Moves to Make Palindrome
2234Maximum Total Beauty of the Gardens
2472Maximum Number of Non-overlapping Palindrome Substrings
2503Maximum Number of Points From Grid Queries
2565Subsequence With the Minimum Score
2604Minimum Time to Eat All GrainsPremium
2868The Wording GamePremium
2911Minimum Changes to Make K Semi-palindromes
2972Count the Number of Incremovable Subarrays II

Two Pointers pattern FAQ

What is the two pointers pattern?

Two pointers walk the input with two indices whose movement is driven by a comparison rather than by a loop counter, and the whole technique rests on one idea: if the input is ordered, the comparison tells you which pointer cannot possibly be part of the answer, so moving it throws away a whole family of candidates at once.

How many LeetCode problems use the two pointers pattern?

This page lists 201 LeetCode problems that the two pointers pattern applies to: 58 Easy, 118 Medium and 25 Hard. 169 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the two pointers pattern?

O(n), or O(n log n) when the input has to be sorted first time and O(1) space. Each pointer only ever moves in one direction, so between them they take at most n steps and the scan is linear. When the input arrives unsorted the sort dominates and the whole solution is O(n log n) — worth saying out loud, because it is exactly the difference between this and a hash-map solution that stays linear. The extra space is two integers, and the fast-and-slow variant on a linked list is likewise O(1), which is normally the constraint being tested.

When should I use the two pointers pattern in an interview?

The input is sorted, or sorting it first does not destroy the answer. You are looking for a pair, triple, or a partition point rather than a subarray.

Which two pointers problem should I start with?

LeetCode 26. Remove Duplicates from Sorted Array is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to two pointers?

Sliding Window, Sorting, Binary Search, Linked List. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.