The task:
You are given an array of length n + 1 whose elements belong to the set {1, 2, ..., n}. By the pigeonhole principle, there must be a duplicate. Find it in linear time and space.
const lst = [1,2,3,4,5,6,7,8,7];
My functional solution:
const findDuplicate = lst => {
const set = new Set();
let ret;
lst.some(x => set.has(x) ?
!Boolean(ret = x) :
!Boolean(set.add(x))
);
return ret;
};
console.log(findDuplicate(lst));
My imperative solutions:
function findDuplicate2(lst) {
const set = new Set();
let i = 0;
while(!set.has(lst[i])) { set.add(lst[i++]); }
return lst[i];
}
console.log(findDuplicate2(lst));
function findDuplicate3(lst) {
for (let i = 0, len = lst.length; i < len; i++) {
if (lst[Math.abs(lst[i])] >= 0) {
lst[Math.abs(lst[i])] = -lst[Math.abs(lst[i])];
} else {
return Math.abs(lst[i]);
}
}
}
console.log(findDuplicate3(lst));
findDuplicate3
O(1) space? I don't use an additional variable - only the running variablei
. \$\endgroup\$imperative solution
, I didn't expect nor notice more than one - even eye-balling it has to wait till after "day-time chores". \$\endgroup\$