educative.io

Solution(s) Based on Actual Question (removing not shifting) + variations

If this is an easy question and the goal is to remove duplicates the quickest solution is to use the built in filter method. Shifting elements in place seems a bit more like a “medium” problem.

Built in solution

function remove_duplicates(arr) {
    const newArray = arr.filter((element, index) => {
    return element !== arr[index - 1];
  });
  return newArray.length;
}

A slightly more hands on approach
that uses “two” iterators - current index and previous index.

function remove_duplicates(arr) {
  let newArray = [];
  for(let iterator = 0; iterator < arr.length; iterator++) {
    if(arr[iterator] !== arr[iterator - 1]) {
      newArray.push(arr[iterator])
    }
  }
  return newArray.length
}

Solving Problem Without Modification
You can also get the “correct” output by counting dups next to each other and subtracting the total length. The question really is asking to do more than you need for the solution. You’re just need to return the difference between the array length and number of dups next to each other, not the actual array. For example adjacent numbers produces the following, [3, 3] = 1 but [3, 3, 3] = 2, [3, 3, 3, 3] = 3 so [2, 3, 3, 3, 3] where array length is 5 and dups are 3 to get a difference of 2!

function remove_duplicates(arr) {
  let first = 0;
  let dupCounter = 0;
  for(let next = 1; next < arr.length; next++) {
    if(arr[first] === arr[next]) {
      dupCounter += 1;
    }
    first += 1;
  }
  return arr.length - dupCounter;
}

Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: https://www.educative.io/courses/grokking-the-coding-interview/mEEA22L5mNA