◻️Pair with Target Sum (easy)

Problem Statement

Given an array of numbers sorted in ascending order and a target sum, find a pair in the array whose sum is equal to the given target.

Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. If no such pair exists return [-1, -1].

Example 1:

Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6

Example 2:

Input: [2, 5, 9, 11], target=11
Output: [0, 2]
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11

Solutions

Approach (2 Pointer)

Runtime 0.009 ms

using namespace std;

#include <iostream>
#include <vector>

class Solution {

  public:

  static vector<int> search(const vector<int> &arr, int targetSum) {
    int ptr_sum=0, n=arr.size();
        int left=0, right=n-1;
        while(left<right){
            ptr_sum=arr[left]+arr[right];
            if(ptr_sum>targetSum){
                right=right-1;
            }
            else if(ptr_sum == targetSum){
                return vector<int> {left, right};
            }
            else{
                left=left+1;
            }
        }
        return vector<int> {-1, -1};
  }

};

Last updated