PROBLEM DESCRIPTION
Given an array A of integers and another non negative integer B . Find if there exists 2 indices i and j such that A[i] - A[j] = B and i != j.
SOLUTION
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
public int diffPossible(final int[] A, int B) {
int n = A.length;
Set<Integer> set = new HashSet<>();
for(int i=0; i<n; i++){
//let's say that we fix the first element x. And second number which we would need is y.
//So, either:
//x - y = B OR y - x = B
//=> y = x - B or y = B + x
int x = A[i];
if(set.contains(x - B) || set.contains(B + x)){
return 1;
}else{
set.add(x);
}
}
return 0;
}
}