Hi,
This is a O(n^2) problem. No other solution is faster than comparing the two arrays directly.
The Virgil's solution is cool, except for the fact that it is not really O(n) performance. It is really O(n+1000) performance. The array comparison second time to set the boolean variable is costly and backfires in small arrays.
The solution you wrote is the best except for a bugs.
Here is the error corrected version.
boolean[] matchedPositions = new boolean[n];
for(int k = 0; k < n; k++
{
matchedPositions[k] = false;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(matchedPositions[j] == false && a[i] == a[j])
{
matchedPositions[j] = true;
break;
}
if(j == n - 1)
{
return false;
}
}
}
return true;
In this case if in case the integer matches then the inner loop will break and set or flag the matched position. This is required for arrays with duplicate entries, this will avoid two entries in left array matching with one entry in the right array.
If in case the match did not happen, which is identified by j == n - 1, you will return false.
Since we are expecting a default value of false in boolean its better to flag initialize it.
In reality, this solution has O(n log n + n) performance penalty. Sort and compare has a performance penalty of O(n^2 + n) too. Sort has O(n^2) performance and one loop for checking. But sorting changes the contents of the array and this does not.