DEV Community

Discussion on: Google Javascript Interview Question - Remove Duplicates from Sorted Array

Collapse
 
leonardosnt profile image
Leonardo Santos

If you want to know how to do it in constant space (and linear time):

function removeDuplicates(arr) {
  let nextNonDuplicate = 0;

  for (let i = 0; i < arr.length; i++) {
    // If this is the last element or it's different from the next one we move it.
    if ((i >= arr.length - 1) || (arr[i] != arr[i + 1])) {
      arr[nextNonDuplicate++] = arr[i];
    }
  }

  arr.length = nextNonDuplicate;
}

You can think of nextNonDuplicate as the index of a new array, if we were using a secondary array to store the non duplicated elements.