Remove the duplicates in-place such that each unique element appears only once

chandrapenugonda

chandra penugonda

Posted on July 23, 2023

Remove the duplicates in-place such that each unique element appears only once

Good morning! Here's your coding interview problem for today.

This problem was asked by Tencent.

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Example

function removeDuplicates(nums){

}

console.log(removeDuplicates([1, 2, 3, 1, 3])) 
// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Solution

function removeDuplicates(nums) {
  const set = new Set();

  for (let i = 0; i < nums.length; i++) {
    set.add(nums[i]);
  }

  let k = 0;
  for (const num of set) {
    nums[k++] = num;
  }
  nums.length = k;
  return k;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Use a Set to collect only unique elements from the unsorted array.
  • Loop over the original array and add each element to the Set.
  • Set will only contain unique elements, discarding duplicates.
  • Loop over Set to rebuild array with only uniques in original order.
  • set size of array to k
  • Return k which is the new length after removing duplicates.
💖 💪 🙅 🚩
chandrapenugonda
chandra penugonda

Posted on July 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related