Skills101
← All coding problems

Two Sum II – Input Array Is Sorted

mediumTwo Pointers+20 XPTime limit 2s

The array is sorted in non-decreasing order. Find the two positions i < j with a[i] + a[j] = target. Exactly one such pair exists. Positions are 1-based in this problem.

Input:

  • line 1: n
  • line 2: n sorted integers
  • line 3: target

Output: i j (1-based, i < j).

Constraints: 2 ≤ n ≤ 10⁵, −10⁹ ≤ a[i], target ≤ 10⁹.

Challenge: the array is sorted, so you don't need a hash map: start one pointer at each end. If the sum is too small, move the left pointer right; if too big, move the right pointer left. O(n) time, O(1) memory.

Sample input 1

4
2 7 11 15
9

Sample output 1

1 2

Sample input 2

3
2 3 4
6

Sample output 2

1 3

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.