The Difference of 2 in Java


The challenge

The objective is to return all pairs of integers from a given array of integers that have a difference of 2.

The resulting array should be sorted in ascending order of values.

Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.

Examples:

[1, 2, 3, 4]  should return [[1, 3], [2, 4]]
[4, 1, 2, 3]  should also return [[1, 3], [2, 4]]
[1, 23, 3, 4, 7] should return [[1, 3]]
[4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]]

The solution in Java code

Option 1:

import java.util.*;
import java.util.stream.*;

public class Challenge {
  public static int[][] twosDifference(int[] a) {
    var s = Arrays.stream(a).boxed().collect(Collectors.toSet());
    return Arrays.stream(a).boxed().filter(x -> s.contains(x + 2)).sorted().map(x -> new int[]{x, x + 2}).toArray(int[][]::new);
  }
}

Option 2:

import static java.util.Arrays.*;
import java.util.*;

public class Challenge {
  public static int[][] twosDifference(int[] array) {
    sort(array);
    final List<int[]> result = new LinkedList<>();
    for (int number : array) {
      int search = number - 2;
      if (binarySearch(array, search) >= 0) {
        result.add(new int[]{search, number});
      }
    }
    return result.toArray(new int[][] {});
  }
}

Option 3:

import static java.util.stream.IntStream.of;
import static org.apache.commons.lang3.ArrayUtils.contains;

interface Challenge {
  static int[][] twosDifference(int[] array) {
    return of(array).filter(i -> contains(array, i + 2)).sorted().mapToObj(i -> new int[]{i, i + 2}).toArray(int[][]::new);
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class Tests {
  @Test
  public void sample_tests() {
    assertArrayEquals(
      new int[][]{{1, 3}, {2, 4}},
      Challenge.twosDifference(new int[]{1, 2, 3, 4})
    );
    assertArrayEquals(
      new int[][]{{1, 3}, {4, 6}},
      Challenge.twosDifference(new int[]{1, 3, 4, 6})
    );
  }
}