Coding Challenge Practice - Question 105

Published: (January 17, 2026 at 04:41 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem

Create a function that removes duplicate values from an array in‑place (i.e., without allocating a new array).

Approach

  1. Use a Set (seen) to keep track of values that have already been encountered.
  2. Iterate through the array with a read pointer (readIndex).
  3. Maintain a write pointer (writeIndex) that points to the position where the next unique element should be placed.
  4. When an element has not been seen before:
    • Add it to seen.
    • Copy it to arr[writeIndex] (if writeIndex differs from readIndex).
    • Increment writeIndex.
  5. 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;
}
Back to Blog

Related posts

Read more »

Coding Challenge Practice - Question 97

Problem Description The task is to find the k‑th largest element in an unsorted array that may contain duplicates. The k‑th largest element is the element that...