Two Pointers Pattern: Template + 201 LeetCode Problems

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

  • 58 Easy
  • 118 Medium
  • 25 Hard
  • O(n), or O(n log n) when the input has to be sorted first time

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.

Two Pointers — Python 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.

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)

#ProblemDifficultyTopics
26Remove Duplicates from Sorted ArrayEasyArray, Two Pointers
27Remove ElementEasyArray, Two Pointers
28Find the Index of the First Occurrence in a StringEasyTwo Pointers, String, String Matching
88Merge Sorted ArrayEasyArray, Two Pointers, Sorting
125Valid PalindromeEasyTwo Pointers, String
141Linked List CycleEasyHash Table, Linked List, Two Pointers
160Intersection of Two Linked ListsEasyHash Table, Linked List, Two Pointers
202Happy NumberEasyHash Table, Math, Two Pointers
234Palindrome Linked ListEasyStack, Recursion, Linked List +1
283Move ZeroesEasyArray, Two Pointers
344Reverse StringEasyTwo Pointers, String
345Reverse Vowels of a StringEasyTwo Pointers, String
349Intersection of Two ArraysEasyArray, Hash Table, Two Pointers +2
350Intersection of Two Arrays IIEasyArray, Hash Table, Two Pointers +2
392Is SubsequenceEasyTwo Pointers, String, Dynamic Programming
455Assign CookiesEasyGreedy, Array, Two Pointers +1
541Reverse String IIEasyTwo Pointers, String
557Reverse Words in a String IIIEasyTwo Pointers, String
653Two Sum IV - Input is a BSTEasyTree, Depth-First Search, Breadth-First Search +4
680Valid Palindrome IIEasyGreedy, Two Pointers, String
696Count Binary SubstringsEasyTwo Pointers, String
876Middle of the Linked ListEasyLinked List, Two Pointers
1768Merge Strings AlternatelyEasyTwo Pointers, String
170Two Sum III - Data structure designPremiumEasyDesign, Array, Hash Table +2
246Strobogrammatic NumberPremiumEasyHash Table, Two Pointers, String
408Valid Word AbbreviationPremiumEasyTwo Pointers, String
821Shortest Distance to a CharacterEasyArray, Two Pointers, String
832Flipping an ImageEasyBit Manipulation, Array, Two Pointers +2
844Backspace String CompareEasyStack, Two Pointers, String +1
905Sort Array By ParityEasyArray, Two Pointers, Sorting
917Reverse Only LettersEasyTwo Pointers, String
922Sort Array By Parity IIEasyArray, Two Pointers, Sorting
925Long Pressed NameEasyTwo Pointers, String
942DI String MatchEasyGreedy, Array, Two Pointers +1
977Squares of a Sorted ArrayEasyArray, Two Pointers, Sorting
1089Duplicate ZerosEasyArray, Two Pointers
1099Two Sum Less Than KPremiumEasyArray, Two Pointers, Binary Search +1
1332Remove Palindromic SubsequencesEasyTwo Pointers, String
1346Check If N and Its Double ExistEasyArray, Hash Table, Two Pointers +2
1385Find the Distance Value Between Two ArraysEasyArray, Two Pointers, Binary Search +1
1455Check If a Word Occurs As a Prefix of Any Word in a SentenceEasyTwo Pointers, String, String Matching
1826Faulty SensorPremiumEasyArray, Two Pointers
1961Check If String Is a Prefix of ArrayEasyArray, Two Pointers, String
2000Reverse Prefix of WordEasyStack, Two Pointers, String
2108Find First Palindromic String in the ArrayEasyArray, Two Pointers, String
2200Find All K-Distant Indices in an ArrayEasyArray, Two Pointers
2367Number of Arithmetic TripletsEasyArray, Hash Table, Two Pointers +1
2441Largest Positive Integer That Exists With Its NegativeEasyArray, Hash Table, Two Pointers +1
2460Apply Operations to an ArrayEasyArray, Two Pointers, Simulation
2465Number of Distinct AveragesEasyArray, Hash Table, Two Pointers +1
2511Maximum Enemy Forts That Can Be CapturedEasyArray, Two Pointers
2540Minimum Common ValueEasyArray, Hash Table, Two Pointers +1
2562Find the Array Concatenation ValueEasyArray, Two Pointers, Simulation
2570Merge Two 2D Arrays by Summing ValuesEasyArray, Hash Table, Two Pointers
2697Lexicographically Smallest PalindromeEasyGreedy, Two Pointers, String
2824Count Pairs Whose Sum is Less than TargetEasyArray, Two Pointers, Binary Search +1
2903Find Indices With Index and Value Difference IEasyArray, Two Pointers
2970Count the Number of Incremovable Subarrays IEasyArray, Two Pointers, Binary Search +1

Medium (118)

#ProblemDifficultyTopics
5Longest Palindromic SubstringMediumTwo Pointers, String, Dynamic Programming
11Container With Most WaterMediumGreedy, Array, Two Pointers
153SumMediumArray, Two Pointers, Sorting
163Sum ClosestMediumArray, Two Pointers, Sorting
184SumMediumArray, Two Pointers, Sorting
19Remove Nth Node From End of ListMediumLinked List, Two Pointers
31Next PermutationMediumArray, Two Pointers
61Rotate ListMediumLinked List, Two Pointers
75Sort ColorsMediumArray, Two Pointers, Sorting
80Remove Duplicates from Sorted Array IIMediumArray, Two Pointers
82Remove Duplicates from Sorted List IIMediumLinked List, Two Pointers
86Partition ListMediumLinked List, Two Pointers
142Linked List Cycle IIMediumHash Table, Linked List, Two Pointers
143Reorder ListMediumStack, Recursion, Linked List +1
148Sort ListMediumLinked List, Two Pointers, Divide and Conquer +2
151Reverse Words in a StringMediumTwo Pointers, String
165Compare Version NumbersMediumTwo Pointers, String
167Two Sum II - Input Array Is SortedMediumArray, Two Pointers, Binary Search
189Rotate ArrayMediumArray, Math, Two Pointers
287Find the Duplicate NumberMediumBit Manipulation, Array, Two Pointers +1
443String CompressionMediumTwo Pointers, String
457Circular Array LoopMediumArray, Hash Table, Two Pointers
475HeatersMediumArray, Two Pointers, Binary Search +1
481Magical StringMediumTwo Pointers, String
522Longest Uncommon Subsequence IIMediumArray, Hash Table, Two Pointers +2
524Longest Word in Dictionary through DeletingMediumArray, Two Pointers, String +1
532K-diff Pairs in an ArrayMediumArray, Hash Table, Two Pointers +2
556Next Greater Element IIIMediumMath, Two Pointers, String
567Permutation in StringMediumHash Table, Two Pointers, String +1
581Shortest Unsorted Continuous SubarrayMediumStack, Greedy, Array +3
611Valid Triangle NumberMediumGreedy, Array, Two Pointers +2
633Sum of Square NumbersMediumMath, Two Pointers, Binary Search
647Palindromic SubstringsMediumTwo Pointers, String, Dynamic Programming
658Find K Closest ElementsMediumArray, Two Pointers, Binary Search +3
763Partition LabelsMediumGreedy, Hash Table, Two Pointers +1
1679Max Number of K-Sum PairsMediumArray, Hash Table, Two Pointers +1
2095Delete the Middle Node of a Linked ListMediumLinked List, Two Pointers
2130Maximum Twin Sum of a Linked ListMediumStack, Linked List, Two Pointers
2300Successful Pairs of Spells and PotionsMediumArray, Two Pointers, Binary Search +1
2462Total Cost to Hire K WorkersMediumArray, Two Pointers, Simulation +1
161One Edit DistancePremiumMediumTwo Pointers, String
186Reverse Words in a String IIPremiumMediumTwo Pointers, String
244Shortest Word Distance IIPremiumMediumDesign, Array, Hash Table +2
251Flatten 2D VectorPremiumMediumDesign, Array, Two Pointers +1
253Meeting Rooms IIPremiumMediumGreedy, Array, Two Pointers +3
2593Sum SmallerPremiumMediumArray, Two Pointers, Binary Search +1
277Find the CelebrityPremiumMediumGraph, Two Pointers, Interactive
360Sort Transformed ArrayPremiumMediumArray, Math, Two Pointers +1
723Candy CrushPremiumMediumArray, Two Pointers, Matrix +1
777Swap Adjacent in LR StringMediumTwo Pointers, String
786K-th Smallest Prime FractionMediumArray, Two Pointers, Binary Search +2
795Number of Subarrays with Bounded MaximumMediumArray, Two Pointers
809Expressive WordsMediumArray, Two Pointers, String
825Friends Of Appropriate AgesMediumArray, Two Pointers, Binary Search +1
826Most Profit Assigning WorkMediumGreedy, Array, Two Pointers +2
838Push DominoesMediumTwo Pointers, String, Dynamic Programming
845Longest Mountain in ArrayMediumArray, Two Pointers, Dynamic Programming +1
870Advantage ShuffleMediumGreedy, Array, Two Pointers +1
881Boats to Save PeopleMediumGreedy, Array, Two Pointers +1
9233Sum With MultiplicityMediumArray, Hash Table, Two Pointers +2
948Bag of TokensMediumGreedy, Array, Two Pointers +1
962Maximum Width RampMediumStack, Array, Two Pointers +1
969Pancake SortingMediumGreedy, Array, Two Pointers +1
986Interval List IntersectionsMediumArray, Two Pointers, Line Sweep
1023Camelcase MatchingMediumTrie, Array, Two Pointers +2
1048Longest String ChainMediumArray, Hash Table, Two Pointers +3
1055Shortest Way to Form StringPremiumMediumGreedy, Two Pointers, String +1
1214Two Sum BSTsPremiumMediumStack, Tree, Depth-First Search +4
1229Meeting SchedulerPremiumMediumArray, Two Pointers, Sorting
1237Find Positive Integer Solution for a Given EquationMediumMath, Two Pointers, Binary Search +1
1265Print Immutable Linked List in ReversePremiumMediumStack, Recursion, Linked List +1
1471The k Strongest Values in an ArrayMediumArray, Two Pointers, Sorting
1498Number of Subsequences That Satisfy the Given Sum ConditionMediumArray, Two Pointers, Binary Search +1
1508Range Sum of Sorted Subarray SumsMediumArray, Two Pointers, Binary Search +2
1570Dot Product of Two Sparse VectorsPremiumMediumDesign, Array, Hash Table +1
1574Shortest Subarray to be Removed to Make Array SortedMediumStack, Array, Two Pointers +2
1577Number of Ways Where Square of Number Is Equal to Product of Two NumbersMediumArray, Hash Table, Math +1
1616Split Two Strings to Make PalindromeMediumTwo Pointers, String
1634Add Two Polynomials Represented as Linked ListsPremiumMediumLinked List, Math, Two Pointers
1650Lowest Common Ancestor of a Binary Tree IIIPremiumMediumTree, Hash Table, Two Pointers +1
1712Ways to Split Array Into Three SubarraysMediumArray, Two Pointers, Binary Search +1
1721Swapping Nodes in a Linked ListMediumLinked List, Two Pointers
1750Minimum Length of String After Deleting Similar EndsMediumTwo Pointers, String
1754Largest Merge Of Two StringsMediumGreedy, Two Pointers, String
1764Form Array by Concatenating Subarrays of Another ArrayMediumGreedy, Array, Two Pointers +1
1813Sentence Similarity IIIMediumArray, Two Pointers, String
1850Minimum Adjacent Swaps to Reach the Kth Smallest NumberMediumGreedy, Two Pointers, String
1855Maximum Distance Between a Pair of ValuesMediumArray, Two Pointers, Binary Search
1861Rotating the BoxMediumArray, Two Pointers, Matrix
1868Product of Two Run-Length Encoded ArraysPremiumMediumArray, Two Pointers
1877Minimize Maximum Pair Sum in ArrayMediumGreedy, Array, Two Pointers +1
1885Count Pairs in Two ArraysPremiumMediumArray, Two Pointers, Binary Search +1
1898Maximum Number of Removable CharactersMediumArray, Two Pointers, String +1
1963Minimum Number of Swaps to Make the String BalancedMediumStack, Greedy, Two Pointers +1
2046Sort Linked List Already Sorted Using Absolute ValuesPremiumMediumLinked List, Two Pointers, Sorting
2105Watering Plants IIMediumArray, Two Pointers, Simulation
2109Adding Spaces to a StringMediumArray, Two Pointers, String +1
2110Number of Smooth Descent Periods of a StockMediumArray, Math, Two Pointers +2
2149Rearrange Array Elements by SignMediumArray, Two Pointers, Simulation
2161Partition Array According to Given PivotMediumArray, Two Pointers, Simulation
2330Valid Palindrome IVPremiumMediumTwo Pointers, String
2332The Latest Time to Catch a BusMediumArray, Two Pointers, Binary Search +1
2337Move Pieces to Obtain a StringMediumTwo Pointers, String
2396Strictly Palindromic NumberMediumBrainteaser, Math, Two Pointers
2406Divide Intervals Into Minimum Number of GroupsMediumGreedy, Array, Two Pointers +3
2410Maximum Matching of Players With TrainersMediumGreedy, Array, Two Pointers +1
2422Merge Operations to Turn Array Into a PalindromePremiumMediumGreedy, Array, Two Pointers
2486Append Characters to String to Make SubsequenceMediumGreedy, Two Pointers, String
2491Divide Players Into Teams of Equal SkillMediumArray, Hash Table, Two Pointers +1
2563Count the Number of Fair PairsMediumArray, Two Pointers, Binary Search +1
2576Find the Maximum Number of Marked IndicesMediumGreedy, Array, Two Pointers +2
2592Maximize Greatness of an ArrayMediumGreedy, Array, Two Pointers +1
2674Split a Circular Linked ListPremiumMediumLinked List, Two Pointers
2825Make String a Subsequence Using Cyclic IncrementsMediumTwo Pointers, String
2838Maximum Coins Heroes Can CollectPremiumMediumArray, Two Pointers, Binary Search +2
2856Minimum Array Length After Pair RemovalsMediumGreedy, Array, Hash Table +3
2905Find Indices With Index and Value Difference IIMediumArray, Two Pointers
2938Separate Black and White BallsMediumGreedy, Two Pointers, String

Hard (25)

#ProblemDifficultyTopics
42Trapping Rain WaterHardStack, Array, Two Pointers +2
295Find Median from Data StreamHardDesign, Two Pointers, Data Stream +2
321Create Maximum NumberHardStack, Greedy, Array +2
719Find K-th Smallest Pair DistanceHardArray, Two Pointers, Binary Search +1
272Closest Binary Search Tree Value IIPremiumHardStack, Tree, Depth-First Search +4
1147Longest Chunked Palindrome DecompositionHardGreedy, Two Pointers, String +3
1163Last Substring in Lexicographical OrderHardTwo Pointers, String
1537Get the Maximum ScoreHardGreedy, Array, Two Pointers +1
1697Checking Existence of Edge Length Limited PathsHardUnion Find, Graph, Array +2
1755Closest Subsequence SumHardBit Manipulation, Array, Two Pointers +3
1782Count Pairs Of NodesHardGraph, Array, Hash Table +4
1793Maximum Score of a Good SubarrayHardStack, Array, Two Pointers +2
1842Next Palindrome Using Same DigitsPremiumHardTwo Pointers, String
2035Partition Array Into Two Arrays to Minimize Sum DifferenceHardBit Manipulation, Array, Two Pointers +4
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2122Recover the Original ArrayHardArray, Hash Table, Two Pointers +2
2193Minimum Number of Moves to Make PalindromeHardGreedy, Binary Indexed Tree, Two Pointers +1
2234Maximum Total Beauty of the GardensHardGreedy, Array, Two Pointers +4
2472Maximum Number of Non-overlapping Palindrome SubstringsHardGreedy, Two Pointers, String +1
2503Maximum Number of Points From Grid QueriesHardBreadth-First Search, Union Find, Array +4
2565Subsequence With the Minimum ScoreHardTwo Pointers, String, Binary Search
2604Minimum Time to Eat All GrainsPremiumHardArray, Two Pointers, Binary Search +1
2868The Wording GamePremiumHardGreedy, Array, Math +3
2911Minimum Changes to Make K Semi-palindromesHardTwo Pointers, String, Dynamic Programming
2972Count the Number of Incremovable Subarrays IIHardArray, Two Pointers, Binary Search

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the two pointers problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.