Open In App

Remove duplicates from Sorted Array

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
137 Likes
Like
Report

Given a sorted array arr[] of size n, the goal is to rearrange the array so that all distinct elements appear at the beginning in sorted order. Additionally, return the length of this distinct sorted subarray.

Note: The elements after the distinct ones can be in any order and hold any value, as they don't affect the result.

Examples: 

Input: arr[] = [2, 2, 2, 2, 2]
Output: [2]
Explanation: All the elements are 2, So only keep one instance of 2.

Input: arr[] = [1, 2, 2, 3, 4, 4, 4, 5, 5]
Output: [1, 2, 3, 4, 5]

Input: arr[] = [1, 2, 3]
Output: [1, 2, 3]
Explanation : No change as all elements are distinct.

Using Hash Set - Works for Unsorted Also - O(n) Time and O(n) Space

  • Use a hash set or dictionary to store elements already processed
  • Initialize index of result array as 0.
  • Traverse through the input array. If an element is not in the hash set, put it at the result index and insert into the set.
C++
Java Python C# JavaScript

Output
1 2 3 4 5 

Expected Approach - O(n) Time and O(1) Space

Since the array is sorted, we do not need to maintain a hash set. All occurrences of an element would be consecutive. So we mainly need to check if the current element is same as the previous element or not.

Step by step implementation:

  • Start with idx = 1 (idx is going to hold the index of the next distinct item. Since there is nothing before the first item, we consider it as the first distinct item and begin idx with 1.
  • Loop through the array for i = 0 to n-1.
    • At each index i, if arr[i] is different from arr[i-1], assign arr[idx] = arr[i] and increment idx.
  • After the loop, arr[] contains the unique elements in the first idx positions.
C++
C Java Python C# JavaScript

Output
1 2 3 4 5 


Next Article
Article Tags :
Practice Tags :

Similar Reads