You are currently viewing Remove Duplicates from the Sorted Array [Easy] in Leetcode JS

Remove Duplicates from the Sorted Array [Easy] in Leetcode JS

If you’re planning or already giving interviews for the software engineer position in a tech company, you must have to be well prepared for the data structure and algorithms problems.

This is the 2nd problem of TOP150FAANG problem series. I’ll be providing easy solution which are easy to understand and implement.

The tech company will most probably judge the candidate’s problem-solving skills through DSA problems in the first round itself.

In this article, we will solve one of the most commonly asked interview problems from leetcode.

Remove Duplicates from Sorted Array

Problem Statement

Given a sorted array nums in increasing order, remove the duplicates from the array in-place such that each element appears only once.

Constraints

  • 1 <= nums.length < 3 x 10^4
  • -100 <= nums[i] <= 100
  • nums are sorted in increasing order
  • Removal of duplicates needs to be done on the original array itself i.e in-place space complexity of the solution must be O(1)

Approach

Use a variable which has the index of current unique element.

Idea is – 

  1. first element is always unique
  2. when Arr[i] !== Arr[i-1] then we found next unique element
  3. put the unique element at index j

Implementation

				
					// A is an array
var removeDuplicates = function(A) {
    let j = 1;

    for (let i = 1; i < A.length; i++) {
        if (A[i] !== A[i-1]) {
            A[j++] = A[i]; 
        }
    }

    return j;
};

TC: O(n)
SC: O(1)