Sobes.tech
Junior — Senior

Finding two array elements with the required sum

livecode

Task condition

Given an array of integers, with 1-based indexing, sorted in non-decreasing order. The task is to find a pair of numbers whose sum equals a given target value. Let's denote these elements as arr[i] and arr[j], where 1 ≤ i < j ≤ arr.length. Return their positions as an array of two elements [i, j].

Example 1: Input: arr = [2, 7, 11, 15], target = 9 Output: [1, 2] Explanation: 2 + 7 = 9, so i = 1, j = 2.

Example 2: Input: arr = [-1, 0], target = -1 Output: [1, 2] Explanation: -1 + 0 = -1, so i = 1, j = 2.