# Follow-up: Find number of times that difference of array values are equals to a number

This question is follow-up to this question.

Sample Calculation

10-21=-11
10-34=-24
10-45=-35
10-56=-46
21-10=11     <
21-34=-13
21-45=-24
21-56=-35
34-10=24
34-21=13
34-45=-11
34-56=-22
45-10=35
45-21=24
45-34=11   <<
45-56=-11
56-10=46
56-21=35
56-34=22
56-45=11   <<<


Code

Set<Integer> tchars = new HashSet<>();
int number = 11;
int counter = 0;

Iterator it = tchars.iterator();
while (it.hasNext()) {
Integer inte = (Integer) it.next();
if (tchars.contains(inte + number)) {
System.err.println(inte + " " + number);
counter++;
}
}
System.err.println(counter);


Using a Set is problematic.

First, as pointed out on the original question in @Vogel612's comment, it restricts duplicate values. Second, it also makes your code a lot messier, as you're now grabbing an Iterator, calling .hasNext(), and testing in a while loop instead of using more concise syntax.

I'd just use a List<Integer>, get rid of all the casts, and use a for-each style syntax instead of using the Iterator. Finally, number and counter aren't very meaningful as variable names in the context of this snippet. If they are meaningful in the wider context of wherever this came from so-be-it, but I find something more along the lines of difference and result much clearer.

Something more like this:

List<Integer> tchars = Arrays.asList(10, 21, 34, 45, 56);
int difference = 11;
int result = 0;

for (int test : tchars) {
if (tchars.contains(test + difference)) {
System.err.println(test + " " + difference);
result++;
}
}

System.err.println(result);


Dead simple, and you can see immediately what it is doing.

• What is a complexity of tchars.contains()?
– vnp
Sep 17, 2014 at 5:58
• This code doesn't work, try it on 10, 10, 21, 34, 45, 56 for example. Sep 17, 2014 at 10:39
• @mjolka Good catch on the sign, fixed. Sep 17, 2014 at 12:26
• @vnp - Time complexity is linear, "roughly speaking". Sep 17, 2014 at 12:31
• Using List.contains is not a very good suggestion for performance. The overall complexity of this code is O(n^2). It is possible to do a O(n) solution. Sep 17, 2014 at 17:31