If arrays do not contain duplicates , one way to do this in O(N) is to use Set , which represents the canonical form of the strings in the array. Something like that:
static Set<String> canonicalSet(String[] arr) { Set<String> upperSet = new HashSet<String>(); for (String s : arr) { upperSet.add(s.toUpperCase()); } return upperSet; } static boolean equalsCanonically(String[] arr1, String[] arr2) { return canonicalSet(arr1).equals(canonicalSet(arr2)); }
This is optimal in time.
You can also make variations of this technique to save more space, for example. instead of constructing canonical sets and comparing them, you can build a canonical set for arr1 , and then remove entries from this set in accordance with the elements of arr2 . After that, the set is empty, and you can always find what you need to delete, the two arrays are canonically equal.
static boolean equalsCanonically2(String[] arr1, String[] arr2) { Set<String> canon = canonicalSet(arr1); for (String s : arr2) { if (!canon.remove(s.toUpperCase())) return false; } return canon.isEmpty(); }
You can also do a simple size matching check if you think it's worth it (i.e. if often two arrays don't have the same number of elements).
If there are duplicates in arrays, the Set method will not work as it is. You will need a multiset, and you can either implement your own or use the Google collection.
There is also an O(N log N) way to do this using string sorting. You can sort both arrays and then do a simple linear check. A case-insensitive comparator should be used, and in fact it already exists as String.CASE_INSENSITIVE_ORDER .
static boolean equalsCanonically3(String[] arr1, String[] arr2) { int N = arr1.length; if (arr2.length != N) return false; Arrays.sort(arr1, String.CASE_INSENSITIVE_ORDER); Arrays.sort(arr2, String.CASE_INSENSITIVE_ORDER); for (int i = 0; i < N; i++) { if (String.CASE_INSENSITIVE_ORDER.compare(arr1[i], arr2[i]) != 0) { return false; } } return true; }
This last method works even if arrays contain duplicates. He does it O(N log N) . It sorts the arrays passed as parameters, so if the initial state is important, you want to pass them to clone() .