Intermediate Level

Implement the hasPairWithExactDifference method that checks whether any two values in the array have the required absolute difference.

The input contains an integer array nums, its length size, and an integer diff. Your task is to check whether any two values in the array have an exact absolute difference equal to diff.

Return true if such a pair exists; otherwise return false. For example, in [5,1,9,3] with diff = 4, the pair 5 and 1 has difference 4.

Example 1

Input
nums (int[]) = [5,1,9,3]
size (int) = 4
diff (int) = 4
Returns (boolean) true

Example 2

Input
nums (int[]) = [2,4,6]
size (int) = 3
diff (int) = 5
Returns (boolean) false

Example 3

Input
nums (int[]) = [7,7]
size (int) = 2
diff (int) = 0
Returns (boolean) true

Use a set to remember values that have already been seen.

For each current value, check whether value - diff or value + diff already exists in the set. If yes, a valid pair exists. Otherwise, store the current value and continue.

Pseudocode:

function hasPairWithExactDifference(nums, size, diff):
    seen = empty set
    for each value in nums:
        if value - diff exists in seen:
            return true
        if value + diff exists in seen:
            return true
        add value to seen
    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.