Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Pair with a given sum in a sorted array

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

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.

Where people lose marks

  • Using <= in the loop condition lets the two pointers land on the same element, which would let you use one number twice.
  • On a sorted array a hash map is not wrong, but it spends O(n) memory to ignore information you were handed.
  • Adding two values near 10⁹ overflows 32-bit integers in C++ and Java. Use a 64-bit type for the sum.
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.