/167. Two Sum II - Input Array Is Sorted

167. Two Sum II - Input Array Is Sorted

Medium
Arrays64.7% acceptance

Given a 1-indexed array of integers sorted in non-decreasing order, find two distinct elements whose sum equals a given integer target. Return their indices (1-based) as a list [i, j] with i < j. There is exactly one solution. Do not use extra space beyond constant.

Example 1

Input: sorted_array = [1, 3, 5, 7], target_sum = 8

Output: [2, 3]

Explanation: 3 + 5 = 8, indices are 2 and 3

Example 2

Input: sorted_array = [-5, 0, 5, 10], target_sum = 5

Output: [1, 3]

Explanation: -5 + 10 = 5, indices are 1 and 4

Example 3

Input: sorted_array = [2, 2, 4], target_sum = 4

Output: [1, 2]

Explanation: 2 + 2 = 4, indices are 1 and 2

Constraints

  • 2 <= len(sorted_array) <= 30000
  • -1000 <= sorted_array[i] <= 1000
  • sorted_array is sorted in non-decreasing order
  • -1000 <= target_sum <= 1000
  • Exactly one solution exists
  • Indices returned must be 1-based and i < j
Python (current runtime)

Case 1

Input: sorted_array = [0, 4, 8, 12], target_sum = 12

Expected: [1, 3]

Case 2

Input: sorted_array = [-10, -3, 0, 7], target_sum = -13

Expected: [1, 2]

Case 3

Input: sorted_array = [1, 2, 3, 4, 5], target_sum = 9

Expected: [4, 5]

Case 4

Input: sorted_array = [-1000, 0, 1000], target_sum = 0

Expected: [1, 3]

Case 5

Input: sorted_array = [5, 10], target_sum = 15

Expected: [1, 2]