Learner Level

Implement the findPairWithSortedSum method that checks whether a sorted array contains a pair with the required sum.

The input contains a sorted integer array nums, its length size, and an integer target. Your task is to check whether any two different values in the array add up to target.

Return true if such a pair exists; otherwise, return false. For example, in [1,2,4,6,9] with target 8, the pair 2 + 6 gives the target.

Example 1
Input:
nums (int[]) = [1,2,4,6,9]
size (int) = 5
target (int) = 8
Return:
(boolean) true
Example 2
Input:
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 10
Return:
(boolean) false
Example 3
Input:
nums (int[]) = [2,7]
size (int) = 2
target (int) = 9
Return:
(boolean) true

Use the two-pointer method because the array is sorted.

Place one pointer at the start and another pointer at the end. If their sum equals the target, return true. If the sum is too small, move the left pointer forward to increase the sum. If the sum is too large, move the right pointer backward to decrease the sum.

If both pointers meet without finding a pair, return false.

Pseudocode:

function findPairWithSortedSum(nums, size, target):
    left = 0
    right = size - 1
    while left < right:
        sum = nums[left] + nums[right]
        if sum == target:
            return true
        else if sum < target:
            left++
        else:
            right--
    return false
Run your code to see the result.