I have two arrays of objects which are likely to have the same values, but in a different order, e.g.
{ "cat", "dog", "mouse", "pangolin" }
{ "dog", "pangolin", "cat", "mouse" }
I wish to treat these two arrays as equal. What's the fastest way to test this?
Pseudocode :
I think the only reasonable way is to sort them and then compare.
Sorting requires
O(n logn)
and comparingO(n)
, so that's still a total ofO(n logn)
Convert both arrays to HashSets and use setequals
I can't guarantee that this is the fastest, but it's certainly quite efficient:
EDIT: SaeedAlg and Sandris raise valid points about different frequencies of duplicates causing problems with this approach. I can see two workarounds if this is important (haven't given much thought to their respective efficiencies):
1.Sort the arrays and then compare them sequentially. This approach, in theory, should have quadratic complexity in the worst case. E.g.:
2.Build up a frequency-table of strings in each array and then compare them. E.g.:
I would use a HashSet, assuming there are no duplicates
Edit:
If you just have four elements it might be faster to skip the HashSet and use arr1.Contains in the comparison. Measure and pick the fastest for your array size.
Have you tried something like