Back to DSA track

Two Sum

Given a sorted array, return the 1-indexed positions of the two numbers that add up to the target.

Two Pointers
EASY

Problem intuition

  • The sorted order is the whole unlock here
  • If the current sum is too small, only the left pointer can help.
  • If it is too large, only the right pointer can help
  • That monotonic movement makes the two-pointer solution both correct and optimal after you move past the brute-force baseline.

Solution

The solutions below are ordered from least optimal to most optimal, so you can see the improvement path instead of only the final answer.

Solution 1

Brute force pair scan

  • Check every pair until you find the matching sum.
  • This is simple, but it ignores the fact that the array is already sorted.
  • Time complexity: O(n^2)
    • the nested loops try every possible pair before returning the match.
  • Space complexity: O(1)
    • only loop counters and the returned pair are used as extra storage.

Solution 2

Two pointers

  • Use the sorted property directly instead of scanning every pair.
  • Move the left pointer when the sum is too small and the right pointer when the sum is too large.
  • Time complexity: O(n)
    • each pointer moves inward across the sorted array at most once.
  • Space complexity: O(1)
    • the algorithm keeps only two pointers and a temporary sum.