Given two integer arrays of size N, design an algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
I can think of two ways:
Sort them and compare : O(N.log N + N)
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0. This is O(N). I am not sure if this method will eliminate false positives completely. Thoughts. Better algorithms?
This doesn’t work. Example:
Others have already suggested
HashMapfor an O(n) solution.Here’s an O(n) solution in C# using a
Dictionary<T, int>:In Python you could use the
Counterclass: