Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Two pointers

Pair with a given sum in a sorted array

Easy · Target 10 minutes · Two pointers · Type asked atCitadelBloomberg

You are given an array nums sorted in non-decreasing order and an integer target. Return the indices of the two numbers that add up to target, in increasing order. Exactly one such pair exists, and you may not use the same element twice.

Examples

InputOutputWhy
nums = [2, 7, 11, 15], target = 9[0, 1]2 + 7 = 9.
nums = [1, 3, 4, 5, 7, 11], target = 10[1, 4]3 + 7 = 10. The scan starts at 1 + 11 = 12, which is too big, so the right pointer moves in.

Constraints

  • 2 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • nums is sorted in non-decreasing order
  • Exactly one valid pair exists

Hints

Hint 1

A hash map solves this in O(n) time and O(n) space without using the ordering. The ordering is there for a reason: you can do better on space.

Hint 2

Put one pointer at each end. What does it tell you when the two values sum to more than the target?

Hint 3

If the sum is too big, the only way to shrink it is to move the right pointer left, because the left value is already the smallest available.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.