function repeatedItem {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) return array[i];
}
}
}This implementation does work fine.
However due to the two loops the worst case runtime is of the order n², where n is the length of the array.
function repeatedItem {
const set = new Set();
for (const item of array) {
if (set.has(item)) {
return item;
} else {
set.add(item);
}
}
}Since we only loop through the items in the array once, doing constant work in each loop thanks to the set data structure,
the runtime now falls to the order of n, where n is the length of the array.