CP: Is there a pair?

You are given a sorted list of whole numbers and a target. Say whether two different positions hold numbers that add up to the target.

What to build

Put one index at the left end and one at the right end. If the sum is too small move the left one right; if too large move the right one left; stop when they meet.

Requirements

  • Use two pointers, not two nested loops
  • Print YES or NO

Input

The first line has n and target. The second line has n numbers in increasing order (values may repeat).

Output

YES if some i < j has a[i] + a[j] = target, otherwise NO.

Constraints

2 ≤ n ≤ 200,000. Values and the target are between -10⁹ and 10⁹.

Example

Input:

6 14
1 3 4 6 8 11

Output:

YES

Why it works

When the sum is too small, the left number cannot pair with any remaining number to reach the target, so it can be dropped. The same is true for the right number when the sum is too big. Each step drops one number, so the scan is O(n).

Examples

Example 1 · Input
6 14
1 3 4 6 8 11
Expected output
YES
Example 2 · Input
4 100
1 2 3 4
Expected output
NO

Hints

Hint 1

Use long long for the sum.

Hint 2

while (i < j): compute s; if s == target print YES and stop; if s < target i++; else j--.

Hint 3

If the loop ends with no match, print NO.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long target;
    cin >> n >> target;
    vector<long long> a(n);
    for (auto& x : a) cin >> x;
    int i = 0, j = n - 1;
    while (i < j) {
        long long s = a[i] + a[j];
        if (s == target) {
            cout << "YES\n";
            return 0;
        }
        if (s < target) i++;
        else j--;
    }
    cout << "NO\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Two pointers and sliding windows →