ragingcorgi
ragingcorgi

Reputation: 3468

Java - How to find if 2 arrays are duplicates of each other?

Given 2 arrays, how can one find out quickly if they are identical by value to each other?

For example, arr1 and arr2 are considered to be identical because they contain equal values, while arr2 and arr3 aren't

int[] arr1 = new int[]{-1, 0, 1};
int[] arr2 = new int[] {-1, 0, 1};
int[] arr3 = new int[] {0, -1, 1}; // not identical

What is the quickest way to find out? I know a for loop will work, but can you do faster, say, constant time? HashSet doesn't work, because technically arr1 and arr2 are different objects

Edit1: what if there are N arrays, and we want to filter out the unique ones?

Upvotes: 0

Views: 57

Answers (2)

Aragorn
Aragorn

Reputation: 5289

There's an equals method in the Arrays class, here's the JavaDoc: Arrays.equals

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198093

Arrays.equals will check for content-based equality of two arrays; it is O(n), which is optimal. You can't do better than O(n).

If you want to filter out the unique arrays among n arrays, you might write something like this:

import java.nio.IntBuffer;
int[][] distinctArrays(int[]... arrays) {
  Set<IntBuffer> set = new HashSet<>();
  for (int[] array : arrays) {
    set.add(IntBuffer.wrap(array));
  }
  int[][] result = new int[set.size()][];
  int i = 0;
  for (IntBuffer wrappedArray : set) {
     result[i++] = wrappedArray.array();
  }
  return result;
}

...or, with Java 8...

int[][] distinctArrays(int[]... arrays) {
  return Stream.of(arrays)
    .map(IntBuffer::wrap)
    .distinct()
    .map(IntBuffer::array)
    .toArray(int[][]::new);
 }

Upvotes: 5

Related Questions