Skip to content

Instantly share code, notes, and snippets.

@redVi
Forked from isRuslan/index.js
Created February 7, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save redVi/0645b80c5ed03892e16a05f8bfc43423 to your computer and use it in GitHub Desktop.
Save redVi/0645b80c5ed03892e16a05f8bfc43423 to your computer and use it in GitHub Desktop.
JS: find one unique value from duplicate array
/*
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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment