Removing duplicates from a sorted array of literals in JavaScript



Suppose we are given a sorted array of literals. We are required to write a function that removes all the duplicates from the array in−place such that each element appears only once and returns the new length of the array.

The condition for doing this is that we cannot allocate extra space for another array, we must do this by modifying the input array in−place with O(1) extra memory.

Example

The code for this will be −

const arr = [1, 3, 3, 6, 7, 7, 9, 11, 13];
const removeDuplicates = (arr = []) => {
   let i=0;
   while(i < arr.length − 1){
      let j = i + 1;
      if(arr[i] === arr[j]){
         arr.splice(j,1);
      }else{
         i++;
      }
   };
};
removeDuplicates(arr);
console.log(arr);

Output

And the output in the console will be −

[
   1, 3, 6, 7,
   9, 11, 13
]

Advertisements