Skip to content

Instantly share code, notes, and snippets.

@jtribble
Last active December 18, 2015 01:54
Show Gist options
  • Save jtribble/6c309c434eae6b60b4a9 to your computer and use it in GitHub Desktop.
Save jtribble/6c309c434eae6b60b4a9 to your computer and use it in GitHub Desktop.
// Given an array where all numbers except one are repeated,
// find the number that only occurs once.
const uniqNums = function(list) {
let hash = {};
let uniq = {};
// O(n) - iterate through list
for (let i = 0; i < list.length; i++) {
if (hash.hasOwnProperty(list[i])) {
delete uniq[list[i]];
continue;
}
hash[list[i]] = true;
uniq[list[i]] = true;
}
let results = [];
// O(n) - worst case, every num is unique
for (let n in uniq) {
if (uniq.hasOwnProperty(n)) {
results.push(parseInt(n));
}
}
return results; // or return results[0], if there's only one unique num
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment