DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 105

The task is to create a function that removes duplicates from an array.

The boilerplate code

function deduplicate(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Using the two pointers approach, readIndex will read through the array while writeIndex writes unique elements.

let writeIndex = 0;
Enter fullscreen mode Exit fullscreen mode

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++;
    }
  }
Enter fullscreen mode Exit fullscreen mode

After processing, truncate the array to the new length.

arr.length = writeIndex;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)