Given an array A of integers and another non-negative integer K, find if there exist 2 indices i and j such that A[i] – A[j] = K, i != j.

Example
Input : A : [1 5 3] k : 2 Output : 1 as 3 – 1 = 2

Return 1 if such pair exists or 0 if no pair found.

Solution

The problem can be solved with Hashing. We can maintain HashSet for the visited elements. While iteration we can do a lookup in visited HashSet for the current element with current_element + K and current_element – K, if we found such element present in Visited HashSet means we have pair present which satisfies A[i] – A[j] = K.

Code

Output

1

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.

2 Thoughts on “Find pair with given difference K in the array”

  • In this case output is 2 right.
    such as
    3 – 1 = 2 and 5-3 =2;

    I have shared the sample code here,
    private int diffPossible(List asList, int k) {
    int count = 0 ;
    HashSet visted = new HashSet();
    for(Integer val : asList) {
    if(visted.contains(val+ k) || visted.contains(val – k )){
    count++;

    }
    visted.add(val);
    }
    return count;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *