Skip to content

Instantly share code, notes, and snippets.

@ambergkim
Last active March 2, 2019 22:52
Show Gist options
  • Save ambergkim/4ebf470fee5261454b19b9e1c5aa7942 to your computer and use it in GitHub Desktop.
Save ambergkim/4ebf470fee5261454b19b9e1c5aa7942 to your computer and use it in GitHub Desktop.
O(1) storage
// Storage O(1).
function removeDupes(arr) {
// sort the array
arr = arr.sort((a, b) => {
return a - b;
});
// pointer 1
p1 = 0;
// pointer 2
p2 = 1;
while (p2 < arr.length) {
console.log(`Array at p1:${p1}, p2:${p2}, array: ${arr}`);
// if the two are the same, set the second to undefined.
if (arr[p1] === arr[p2]) {
arr[p2] = undefined;
p2++;
}
// if the first is less than the second, move the first up.
if (arr[p1] < arr[p2]) {
p1++;
}
// if the first is undefined, trade with the second.
if (arr[p1] === undefined) {
arr[p1] = arr[p2];
arr[p2] = undefined;
// move the second up
p2++;
}
}
return arr;
}
console.log('Expected [1, 2, 3, 5, 6, undefined, undefined, undefined]:', '\n Actual [' + removeDupes([
1, 2, 1, 2, 3, 5, 5, 6
]) + ']');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment