Created
July 6, 2015 22:27
-
-
Save isRuslan/4e5171a810a4c5e1db98 to your computer and use it in GitHub Desktop.
JS: find one unique value from duplicate array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given the array of IDs, which contains many duplicate integers | |
and one unique integer, find the unique integer. | |
*/ | |
// O(n^2): loop in loop | |
function find_unique_brute (array) { | |
var result = null, n = array.length; | |
for (var i = 0; i < n; i++) { | |
for (var j = i; j < n; j++) { | |
if (array[i] != array[j]) { | |
result = array[i]; | |
} | |
} | |
} | |
return result; | |
} | |
// O(2n): loop + loop => O(n) + O(n) space | |
function find_unique_hash (array) { | |
var n = array.length; | |
var hash = {}, result = null; | |
for (var i = 0; i < n; i++) { | |
if (array[i] in hash) { | |
hash[array[i]] += 1; | |
} else { | |
hash[array[i]] = 1; | |
} | |
} | |
for (var j in hash) { | |
if (hash[j] == 1) { | |
result = j; | |
} | |
} | |
return result; | |
} | |
// O(n) with no space: deep into Bits for solution | |
function find_unique_xor (array) { | |
var result = 0, n = array.length; | |
for (var i = 0; i < n; i++) { | |
result ^= array[i]; | |
} | |
return result; | |
} | |
var uni1 = find_unique_brute([1, 1, 5, 5, 3, 6, 6]); | |
var uni2 = find_unique_hash([1, 1, 5, 5, 3, 6, 6]); | |
var uni3 = find_unique_xor([1, 1, 5, 5, 3, 6, 6]); | |
console.assert(uni1 == 3, uni1 + ' should eql 3'); | |
console.assert(uni2 == 3, uni2 + ' should eql 3'); | |
console.assert(uni3 == 3, uni3 + ' should eql 3'); | |
console.log('all passed'); |
I like this function: find_unique_hash.
Excellent! Works correctly))
Thanks, interesting!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working 👎