Premium is or
Premium is
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Fixed Length Sliding Window
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Variable Length Sliding Window
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing
Tutor
Get Premium
Two Pointers

Two-Pointer Overview

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
This technique uses two pointers to scan an array in a single pass. Most of the time the pointers start at opposite ends and move towards each other, which is exactly what we'll do in the Two Sum example below. But that isn't the only setup. In some problems the two pointers move in the same direction, each tracking a region of the array (you'll find a few of those in the bonus problems at the bottom).
134681013leftright
In this page, we'll cover:
  1. A simple problem that illustrates the motivation behind the two-pointer technique.
  2. The types of problem for which you should consider using this technique.
  3. A list of problems (with animated solutions!) for you to try that build upon the concepts covered here.

Problem: Two Sum

DESCRIPTION
Given a sorted array of integers nums, determine if there exists a pair of numbers that sum to a given target.
Example: Input: nums = [1,3,4,6,8,10,13], target = 13 Output: True (3 + 10 = 13)
Input: nums = [1,3,4,6,8,10,13], target = 6 Output: False
The naive approach to this problem uses two-pointers i and j in a nested for-loop to consider each pair in the input array, for a total of O(n2) pairs considered.
Visualization
Try these examples:
def isPairSum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return True
return False
134681013

two sum naive

0 / 11

However, if we put a bit more thought into how we initialize our pointers and how we move them, we can eliminate the number of pairs we consider down to O(n). Understanding why we are able to eliminate pairs is key to understanding the two-pointer technique.
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij
134681013ij13
134681013leftright
134681013leftright
134681013leftright13
Naive (left) vs. Two-Pointer Technique (right)

Eliminating Pairs

The two-pointer technique leverages the fact that the input array is sorted.
Let's use it to solve the Two Sum problem when nums = [1, 3, 4, 6, 8, 10, 13] and target = 13.
134681013
Goal: find this pair of numbers that sum to 13
We start by initializing two pointers at opposite ends of the array, which represent the pair of numbers we are currently considering.
134681013
This pair has a sum (14) that is greater than our target (13). And because our array is sorted, all other pairs ending at our right pointer (13) also have sums greater than our target, as they all involve numbers greater than 1, the value at our left pointer.
134681013leftright
So, to move onto the next pair we move our right pointer back, which elimininates those unnecessary pairs from our search.
134681013leftright1617192123
Move right pointer back.
Now, since our sum is less than our target, we know that all other pairs involving our left pointer also have sums less than our target. So, we move our left pointer forward to eliminate those unnecessary pairs and arrive at the next pair to consider.
134681013leftright
This continues until either our pointers meet (in which case we did not find a successful pair) or until we find a pair that sums to our target, like we did here.
134681013leftright

Solution

Visualization
Try these examples:
def twoSum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return True
if current_sum < target:
left += 1
else:
right -= 1
return False
134681013

two sum algorithm

0 / 7

Summary

  • The two-pointer technique leverages the fact that the input array is sorted to eliminate the number of pairs we consider from O(n2)down to O(n).
  • The two-pointers start at opposite ends of the array, and represent the pair of numbers we are currently considering.
  • We repeatedly compare the sum of the current pair to the target, and move a pointer in a way that eliminates unnecessary pairs from our search.

When Do I Use This?

Consider using the two-pointer technique for questions that involve searching for a pair (or more) of items in an array that meet a certain criteria.
Examples:
  • Finding a pair of items that sum to a given target in an array.
  • Finding a triplet of items that sum to 0 in a given array.
  • Finding the maximum amount of water that can be held between two array items representing wall heights.

Practice Problems

Try applying the concepts related to eliminating unnecessary pairs to the following problems:
DoneQuestionDifficulty
Container With Most Water
Medium
3-Sum
Medium
Triangle Numbers
Medium

Bonus: Additional Problems

These problems also use two pointers in an array, but instead, each pointer represents a logical "region" of the array.
DoneQuestionDifficulty
Move Zeroes
Easy
Sort Colors
Medium
Trapping Rain Water
Hard
Test Your Knowledge

Answer the question below to find your gaps.

Mark as read
Next: Container With Most Water

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Problem: Two Sum

Eliminating Pairs

Solution

Summary

When Do I Use This?

Practice Problems

Bonus: Additional Problems

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsAnthropic SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103

© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress