Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates from Array

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a JavaScript program to remove duplicates from a sorted array in-place. Return the length of the array after removing duplicates. The relative order of elements should be maintained, and you should modify the original array.

Example 1
  • Input: nums = [1,1,2]
  • Output: 2, nums = [1,2,_]
  • Explanation:
    • The array has duplicate 1's at positions 0 and 1.
    • Keep the first occurrence of 1 and the unique element 2.
    • The first 2 elements of the modified array are [1,2].
    • Return length 2 as there are 2 unique elements.
Example 2
  • Input: nums = [0,0,1,1,1,2,2,3,3,4]
  • Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
  • Explanation:
    • The array has multiple duplicates.
    • Keep only the first occurrence of each unique element.
    • The first 5 elements become [0,1,2,3,4].
    • Return length 5 as there are 5 unique elements.
Constraints
  • 1 ≤ nums.length ≤ 3 * 10^4
  • -100 ≤ nums[i] ≤ 100
  • nums is sorted in non-decreasing order
  • You must modify the array in-place with O(1) extra memory
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysShopifyArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers approach - one slow pointer and one fast pointer
  • The slow pointer keeps track of the position for the next unique element
  • The fast pointer scans through the array to find unique elements
  • Compare consecutive elements to identify duplicates
  • When a unique element is found, place it at the slow pointer position
  • Increment the slow pointer only when a unique element is placed
  • Return the slow pointer value as it represents the length of unique elements

Steps to solve by this approach:

 Step 1: Handle edge case - if the array is empty, return 0.
 Step 2: Initialize slow pointer to 1 since the first element is always unique.
 Step 3: Use fast pointer to iterate through the array starting from index 1.
 Step 4: Compare current element with the previous element to check for duplicates.
 Step 5: If elements are different, copy the current element to the slow pointer position.
 Step 6: Increment the slow pointer to point to the next position for unique elements.
 Step 7: Return the slow pointer value which represents the count of unique elements.

Submitted Code :