I recently saw this Javascript code on StackOverflow for merging two arrays, and removing duplicates:
Array.prototype.unique = function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var array3 = array1.concat(array2).unique();
While this code works, it is horribly inefficient (O(n^2)
). Your challenge is to make an algorithm with less complexity.
The winning criteria is the solution with the least complexity, but ties will be broken by shortest length in characters.
Requirements:
Package all your code together in a function that meets the following requirements for "correctness:"
- Input: Two arrays
- Output: One array
- Merges elements of both arrays together- Any element in either input array must be in the outputted array.
- The outputted array should have no duplicates.
- Order doesn't matter (unlike the original)
- Any language counts
- Don't use the standard library's array functions for detecting uniqueness or merging sets/arrays (although other things from the standard library is okay). Let me make the distinction that array concatenation is fine, but functions that already do all of the above are not.
[1, 2, 2, 3]
and[2, 3, 4]
return[1, 2, 2, 3, 4]
or[1, 2, 3, 4]
? \$\endgroup\$