Last active
March 2, 2019 21:59
-
-
Save ambergkim/ad4ded08b163ba8f45a49be6bb2c22c8 to your computer and use it in GitHub Desktop.
O(N) Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// O(N) | |
function remDupes(arr) { | |
// have we seen this? | |
let hash = []; | |
// pointer 1 | |
p = -1; | |
// establish i as pointer 2 | |
for (let i = 0; i < arr.length; i++) { | |
console.log('arr at: ', i, arr); | |
// if we haven't already seen it | |
if (!hash[arr[i]]) { | |
// add it | |
hash[arr[i]] = arr[i]; | |
// move pointer 1 | |
if (p === -1) { | |
p++; | |
// if we made the spot undefined. | |
} else if (arr[p] === undefined) { | |
// pointer 1 location stores pointer 2 location. | |
arr[p] = arr[i]; | |
// set pointer 2 location to undefined. | |
arr[i] = undefined; | |
// move pointer 1 up. | |
p++; | |
} else { | |
// move pointer 1 up. | |
p++; | |
} | |
// if we've seen it before. | |
} else if (hash[arr[i]]) { | |
// erase the duplicate | |
arr[i] = undefined; | |
// if the first pointer is not at an undefined, move it up. | |
if (arr[p] !== undefined) { | |
p++; | |
} | |
} | |
} | |
return arr; | |
} | |
console.log( | |
'Expected [1, 2, 3, 5, 6, undefined, undefined, undefined]:', remDupes([ | |
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