The task:
Given an array of integers in which two elements appear exactly once and all other elements appear exactly twice, find the two elements that appear only once.
For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does not matter.
Follow-up: Can you do this in linear time and constant space?
const lst = [2, 4, 6, 8, 10, 2, 6, 10];
My functional solution
const findUnique = lst => lst
.sort((a,b) => a - b)
.filter((x, i) => lst[i-1] !== x && lst[i+1] !== x);
console.log(findUnique(lst));
My imperative solution:
function findUnique2(lst) {
const res = [];
const map = new Map();
lst.forEach(x => map.set(x, map.get(x) === undefined));
map.forEach((val, key) => {
if(val) { res.push(key); }
});
return res;
}
console.log(findUnique2(lst));
I think the imperative solution is in linear time but not constant space. How would you do it with constant space?
order does not matter
order of inputs or order of results? The example shows exactly one deviation from monotonicity. (My guess: both.) \$\endgroup\$