Skip to content
We areTOP 1%
DSA · Beginner · Pattern 2 of 11

Two Pointers

12 problems.
Your progress0%
1st Visit
0/12
2nd Visit
0/12
Revise
0/12

About this pattern

Two pointers keeps two indices that move through a sequence according to a rule, so that every step discards candidates that cannot be optimal. The common forms are opposite ends moving inward (sorted pair sums, palindromes, partitioning) and a slow and a fast index moving in the same direction (in-place filtering, merging sorted arrays).

Look for a sorted or sortable array, a request for a pair or triplet with a target sum, or a need to compare elements from both ends without extra memory. Because each pointer only moves forward, the scan is O(n) after any O(n log n) sort, with O(1) extra space.

// Opposite ends on a sorted array: find a pair with sum == target.
int lo = 0, hi = (int)a.size() - 1;
while (lo < hi) {
    long long s = (long long)a[lo] + a[hi];
    if (s == target) break;     // found the pair (lo, hi)
    if (s < target) ++lo;       // need a larger sum
    else --hi;                  // need a smaller sum
}

Problems

Two Pointers questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Valid PalindromeLeetCodeEasy Solve Valid Palindrome on LeetCode (opens in a new tab)
2Remove Duplicates from Sorted ArrayLeetCodeEasy Solve Remove Duplicates from Sorted Array on LeetCode (opens in a new tab)
3Merge Sorted ArrayLeetCodeEasy Solve Merge Sorted Array on LeetCode (opens in a new tab)
4Sereja and DimaCodeforcesEasy 800Solve Sereja and Dima on Codeforces (opens in a new tab)
5Prepend and AppendCodeforcesEasy 800Solve Prepend and Append on Codeforces (opens in a new tab)
6Eating CandiesCodeforcesEasy 1100Solve Eating Candies on Codeforces (opens in a new tab)
7Kalindrome ArrayCodeforcesEasy 1100Solve Kalindrome Array on Codeforces (opens in a new tab)
8Alice, Bob and ChocolateCodeforcesEasy 1200Solve Alice, Bob and Chocolate on Codeforces (opens in a new tab)
9Two Sum II - Input Array Is SortedLeetCodeMedium Solve Two Sum II - Input Array Is Sorted on LeetCode (opens in a new tab)
10Sort ColorsLeetCodeMedium Solve Sort Colors on LeetCode (opens in a new tab)
11Container With Most WaterLeetCodeMedium Solve Container With Most Water on LeetCode (opens in a new tab)
123SumLeetCodeMedium Solve 3Sum on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account