author avatar BooleanStack

167. Two Sum II - Input Array Is Sorted

Master the efficient Two Pointer technique to solve the sorted Two Sum problem in linear time and constant space.

Two Sum II - Input Array Is Sorted

You’ve probably seen the classic Two Sum problem before—it’s practically a rite of passage on LeetCode. Most people solve it with a Hash Map, getting that sweet O(n)O(n) time complexity (though at the cost of O(n)O(n) space).

But here’s where Two Sum II gets interesting. There’s one critical difference: the array is already sorted. And that changes everything. We can toss the Hash Map aside completely and solve this with constant O(1)O(1) space while still keeping linear O(n)O(n) time. It’s the perfect introduction to the Two Pointer technique—a pattern you’ll use again and again.

The Problem Statement

You’re given a 1-indexed array of integers called numbers that’s sorted in non-decreasing order. Your job? Find two numbers that add up to a specific target.

Here’s what you need to know:

  1. Return the indices as [index1, index2] where both are 1-indexed.
  2. 1index1<index2numbers.length1 \le index1 < index2 \le numbers.length (the first index must come before the second).
  3. You can’t use the same element twice.
  4. You must use only constant extra space (no Hash Maps this time!).

Real-World Analogy

So you grab the cheapest item (left side) and the most expensive item (right side):

You keep moving inward from both ends until you hit exactly $50. That’s the Two Pointer technique in a nutshell.

Interactive Exploration

Before we jump into code, try finding the target sum yourself with this interactive tool. Pay attention to how the sorted order basically tells you which way to move next.

Two Sum II - Interactive Practice

Quick Test Cases:

Array Editor

2
7
11
15
2
0
7
1
11
2
15
3

History

No actions yet. Start the game!

How to Play

  1. Click "Start Game" to begin
  2. Use "Move Left →" to move the left pointer right
  3. Use "← Move Right" to move the right pointer left
  4. Click "Check Sum" to verify if current sum equals target
  5. Try to find the solution in minimum attempts!

The Optimal Approach: Two Pointers

Sure, you could use Brute Force (O(n2)O(n^2)—yikes) or Binary Search (O(nlogn)O(n \log n)—better, but not optimal). But when you’ve got a sorted array, the Two Pointer technique is the way to go.

How It Works

Here’s the game plan:

  1. Start with two pointers: left at index 0 and right at the last index.
  2. Add up the values at these two positions.
  3. Now compare that sum to your target:
    • Perfect match? You’re done. Return [left + 1, right + 1] (remember the 1-indexing).
    • Sum too small? You need bigger numbers. Since the array’s sorted, move left to the right.
    • Sum too big? You need smaller numbers. Move right to the left.
  4. Keep going until the pointers meet.

The magic here: You never have to backtrack. If numbers[left] + numbers[right] is too big, then numbers[right] is too large to pair with anything from left onward. You can eliminate it permanently and move on.

Visualizing the Algorithm

Watch how the pointers close in on the answer:

Two Sum II - Two Pointers Algorithm

1000ms
Click "Start" to begin the visualization
2
idx: 0
7
idx: 1
11
idx: 2
15
idx: 3

Algorithm Explanation

  1. Start with two pointers: left at the beginning and right at the end
  2. Calculate the sum of elements at both pointers
  3. If sum equals target, return the indices (1-indexed)
  4. If sum is less than target, move left pointer right (increase sum)
  5. If sum is greater than target, move right pointer left (decrease sum)
  6. Repeat until pointers meet or solution is found

Time Complexity: O(n) - Single pass through the array
Space Complexity: O(1) - Only two pointers used

Implementation

Let’s see this in action. Here’s the code in Java, C++, and Python. Notice how we adjust for 1-based indexing in the return statement (just add 1 to our 0-based indices).

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        // Start from both ends
        int left = 0;
        int right = numbers.length - 1;
        
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            
            if (sum == target) {
                // Found it! Convert to 1-based indices
                return new int[]{left + 1, right + 1};
            } else if (sum < target) {
                // Need a bigger sum
                left++;
            } else {
                // Need a smaller sum
                right--;
            }
        }
        
        // We shouldn't get here (problem guarantees a solution exists)
        return new int[]{-1, -1};
    }
}

Comparison of Approaches

Why is Two Pointers better than the alternatives?

Let’s break it down:

  1. Brute Force: Check every possible pair. That’s O(n2)O(n^2). With inputs up to 3×1043 \times 10^4 elements, this’ll time out faster than you can say “nested loop.”
  2. Binary Search: For each element, search for its complement (target - element). This gives you O(nlogn)O(n \log n). Not bad, but we can do better.
  3. Two Pointers: Each element gets visited exactly once. That’s O(n)O(n)—as good as it gets.

Two Sum: Hash Map vs Two Pointers

Hash Map Approach

Array:

2
0
7
1
11
2
15
3

Hash Map:

Empty

Time: O(n) | Space: O(n)
Works on unsorted arrays

Two Pointer Approach

Sorted Array:

2
0
7
1
11
2
15
3

Pointers:

Not started

Time: O(n) | Space: O(1)
Requires sorted array

When to Use Each Approach?

Hash Map

  • Array is unsorted
  • Need to find all pairs (not just one)
  • Space is not a constraint
  • Single pass solution needed

Two Pointers

  • Array is already sorted
  • Space optimization is critical
  • Follow-up requires O(1) space
  • Problem guarantees sorted input

Complexity Analysis

Time Complexity : O(N)

We traverse the array once, max. The left pointer only moves right, right only moves left. They meet somewhere in the middle, doing constant work at each step.

Space Complexity : O(1)

Just two integer variables for our pointers. That’s it. Unlike the original Two Sum, we don’t need a Hash Map because the sorted array is our lookup structure.

Common Pitfalls

Watch out for these gotchas:

  1. 1-Based Indexing: The problem wants 1-based indices, but most languages (Java, Python, C++) use 0-based. Don’t forget to add 1 before returning your answer.
  2. Pointer Movement Logic: Move left right when the sum’s too small. Move right left when it’s too big. Mix this up and you’ll be debugging for a while.
  3. Integer Overflow: Technically, numbers[left] + numbers[right] could overflow in C++ or Java. But the constraints (1000numbers[i]1000-1000 \le numbers[i] \le 1000) keep us safe here.

Conclusion

Two Sum II is a textbook example of how constraints (in this case, a sorted array) can completely transform your approach. The Two Pointer technique gives us the best possible performance—both time and space.

💡 Key takeaway: Whenever you see “sorted array” in a problem, your brain should immediately think “Two Pointers or Binary Search?”

This pattern shows up everywhere3Sum, Container With Most Water, Trapping Rain Water. Get comfortable with it here, and those tougher problems become a lot more manageable.

Similar Posts