The task is to create a function that removes duplicates from an array.
The boilerplate code
function deduplicate(arr) {
// your code here
}
The objective includes removing the duplicates without creating a new array. Track items that have been seen as the array is being sorted
const seen = new Set();
Using the two pointers approach, readIndex will read through the array while writeIndex writes unique elements.
let writeIndex = 0;
When an unseen element is encountered, it is added to the Set and copied to the writeIndex position.
for (let readIndex = 0; readIndex < arr.length; readIndex++) {
const item = arr[readIndex];
if (!seen.has(item)) {
// Mark as seen
seen.add(item);
if (writeIndex !== readIndex) {
arr[writeIndex] = item;
}
writeIndex++;
}
}
After processing, truncate the array to the new length.
arr.length = writeIndex;
The final code
function deduplicate(arr) {
// your code here
const seen = new Set();
let writeIndex = 0;
for(let readIndex = 0; readIndex < arr.length; readIndex++) {
const item = arr[readIndex];
if(!seen.has(item)) {
seen.add(item);
if(writeIndex !== readIndex) {
arr[writeIndex] = item;
}
writeIndex++;
}
}
arr.length = writeIndex;
return arr;
}
That's all folks!
Top comments (0)