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.

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.


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.




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

Leave a Reply

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