Coding Challenge Practice - Question 105
Source: Dev.to
Problem
Create a function that removes duplicate values from an array in‑place (i.e., without allocating a new array).
Approach
- Use a
Set(seen) to keep track of values that have already been encountered. - Iterate through the array with a read pointer (
readIndex). - Maintain a write pointer (
writeIndex) that points to the position where the next unique element should be placed. - When an element has not been seen before:
- Add it to
seen. - Copy it to
arr[writeIndex](ifwriteIndexdiffers fromreadIndex). - Increment
writeIndex.
- Add it to
- After the loop, truncate the array to the new length (
writeIndex).
Implementation
function deduplicate(arr) {
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; // truncate to unique elements
return arr;
}