Solution: Difference

The difference keeps the elements that are in but not in . Unlike union and intersection, it is asymmetric: and are different sets. As before, is the size of and is the size of , and arr1 holds and arr2 holds .

On an unsorted set

Iterate over and keep each element that is not in :

public static int[] difference(int[] arr1, int[] arr2) {
  int[] result = new int[arr1.length];
  int k = 0;
  for (int i = 0; i < arr1.length; i++) {
    if (!contains(arr2, arr1[i])) {
      result[k++] = arr1[i];
    }
  }
  return trim(result, k);
}

This is the intersection with the test negated, and it has the same cost, . Because the difference is asymmetric, we must iterate over . We cannot pick the smaller set to iterate over, the way we could for the intersection.

On a sorted set

We use the merge again, with the keep-rule changed to “in , not in ”:

public static int[] sortedDifference(int[] arr1, int[] arr2) {
  int[] result = new int[arr1.length];
  int i = 0, j = 0, k = 0;
  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] < arr2[j]) {
      result[k++] = arr1[i++];  // in arr1, not in arr2: copy
    } else if (arr1[i] > arr2[j]) {
      j++;                      // in arr2 only: skip
    } else {
      i++;                      // a tie: in both, exclude
      j++;
    }
  }
  while (i < arr1.length) {
    result[k++] = arr1[i++];    // what is left of arr1 is not in arr2
  }
  return trim(result, k);
}

The asymmetry changes the final step of the merge. When the first loop ends, we copy what is left of , because those elements are greater than every element of and so cannot be in it. If still has elements left, the second loop does not run and we discard them. The merge is , and the result is sorted.

Implementation Difference cost
LinkedSet/ArraySet
SortedArraySet

All three operations follow the same pattern. On an unsorted set they cost , because each element of one set is searched for in the other. On a sorted set a single merge computes the result in , and the only thing that changes between union, intersection, and difference is the keep-rule.