![]() |
VOOZH | about |
Given a 1-based indexed integer array arr[] that is sorted in non-decreasing order, along with an integer target. find two elements in the array such that their sum is equal to target. If such a pair exists, return the indices of the two elements in increasing order. If no such pair exists, return [-1, -1].
Examples:
Input: arr[] = [2, 7, 11, 15], target = 9
Output: 1 2
Explanation: Since the array is 1-indexed, arr[1] + arr[2] = 2 + 7 = 9Input: arr[] = [1, 3, 4, 6, 8, 11] target = 10
Output: 3 4
Explanation: Since the array is 1-indexed, arr[3] + arr[5] = 4 + 6 = 10
Table of Content
The idea is to check every possible pair of elements using two nested loops. If any pair adds up to the target, we return their 1-based indices immediately.
1 2
The problem can be solved using two pointers technique. We can maintain two pointers, left = 0 and right = n - 1, and calculate their sum S = arr[left] + arr[right].
- If S = target, then return left and right.
- If S < target, then we need to increase sum S, so we will increment left = left + 1.
- If S > target, then we need to decrease sum S, so we will decrement right = right - 1.
If at any point left >= right, then no pair with sum = target is found.
Step-by-step algorithm:
1 2