Remove Duplicates from Sorted Array(#26)

Category: Array, Two Pointer

🧩 Problem Statement

You’re given a sorted array of integers. You need to remove duplicates in-place so that each element appears only once. Return the number of unique elements `k`, and modify the input array such that the first `k` elements are the unique ones. Their order should be preserved. Values beyond index `k-1` can be ignored.

πŸ“š Examples

Input: nums = [1, 1, 2]

Output: 2

Explanation: Modified array becomes [1, 2, _]. Only first 2 elements matter.

Input: nums = [0,0,1,1,1,2,2,3,3,4]

Output: 5

Explanation: Modified array becomes [0,1,2,3,4,_,_,_,_,_]. First 5 elements are unique.

🧠 Approach

### Two Pointer Approach

We use two pointers `first` and `sec`.

- `first` tracks the position of the last unique element.

- `sec` scans the array for the next unique element.

If we find a new unique number at `sec`, we move `first` forward and swap it with `sec`. At the end, `first + 1` gives the total count of unique elements.

πŸ’» Code

var removeDuplicates = function (nums) {
  let first = 0;
  let sec = 1;

  while (sec < nums.length) {
    if (nums[first] === nums[sec]) {
      sec++;
    } else {
      first++;
      [nums[first], nums[sec]] = [nums[sec], nums[first]];
      sec++;
    }
  }

  console.log(nums.slice(0, first + 1)); // Shows the unique values
  return first + 1;
};

console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4])); // Output: 5

πŸ“ˆ Complexity

Time: O(n) – one pass through the array.

Space: O(1) – in-place solution using no extra space.

🎬 Watch Explanation

πŸ“Š Presentation (PPT)

πŸ“₯ Download PPT

πŸ“Ž Resources