Pair with Target Sum in a Sorted Array

easy Arrays

Problem

The array is sorted in ascending order and has different values. Print the 1-based positions i and j (i < j) of the two numbers whose sum is k, separated by a space. At most one such pair exists. If there is none, print -1.

Constraints

  • 2 <= n <= 10^5
  • values are different
  • |a[i]|, |k| <= 10^9

Examples

Input

4
2 7 11 15
9

Output

1 2

Solutions

Best approachTime O(n)Space O(1)

The array is sorted, so the sum tells us which pointer to move. A small sum needs a bigger number, a big sum needs a smaller one. Each step drops one number for good, so we need only O(n) steps.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find a pair.
 * Input   : n, the sorted array, then k.
 * Output  : Two positions or -1.
 * Approach: Two pointers.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(int[] a, int k) {
        // Step 1: One pointer at the smallest number, one at the biggest.
        int left = 0;
        int right = a.length - 1;
        while (left < right) {
            long sum = (long) a[left] + a[right];
            // Step 2: A sum that is too small needs a bigger left number. A sum that is too big needs a smaller right number.
            if (sum == k) {
                return (left + 1) + " " + (right + 1);
            } else if (sum < k) {
                left++;
            } else {
                right--;
            }
        }
        return "-1";
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (2)
  1. What happens to the sum if the left pointer moves right?
  2. Stop when the pointers meet.