Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates from Sorted Array

Certification: Basic Level Accuracy: 60% Submissions: 15 Points: 5

Write a Java program to remove duplicates from a sorted array. Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Example 1
  • Input: nums = [1,1,2]
  • Output: 2, nums = [1,2,...]
  • Explanation:
    • Only one duplicate removed, array becomes [1,2]
Example 2
  • Input: nums = [0,0,1,1,1,2,2,3,3,4]
  • Output: 5, nums = [0,1,2,3,4,...]
  • Explanation:
    • All duplicates are removed in-place
Constraints
  • 0 ≤ nums.length ≤ 3 * 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • nums is sorted in non-decreasing order
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysWalmartSwiggy
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: one for the current position and one for the non-duplicate array
  • Compare adjacent elements to find duplicates
  • Move unique elements to the front of the array
  • Keep track of the length of the array with non-duplicates
  • Return the new length of the array

Steps to solve by this approach:

 Step 1: Handle the edge case - if the array is empty, return 0.
 Step 2: Initialize a pointer i at index 0, which will track the position where the next unique element should be placed.
 Step 3: Iterate through the array starting from index 1 with another pointer j.
 Step 4: If the current element at index j is different from the element at index i, increment i and copy the element at j to position i.
 Step 5: Continue this process until the end of the array is reached.
 Step 6: Return i+1, which represents the length of the array with unique elements.
 Step 7: The first i+1 elements of the array now contain all the unique elements in the same order they appeared.

Submitted Code :