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
Returns (boolean) true

Example 2

Input
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 10
Returns (boolean) false

Example 3

Input
nums (int[]) = [2,7]
size (int) = 2
target (int) = 9
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.