Remove Duplicatesfrom Sorted Array Algorithm
The Remove Duplicates from Sorted Array Algorithm is an efficient technique used to eliminate duplicate elements from a sorted array, leaving only distinct elements in the original array. This algorithm is particularly useful when dealing with large datasets where duplicate entries are common and need to be removed for further processing or analysis. The primary objective of this algorithm is to modify the input array in-place, such that it contains only unique elements, and return the new length of the modified array. It does not require any additional data structures, making it a space-efficient solution.
The algorithm works by maintaining two pointers, one for reading the elements from the sorted array and the other for storing the unique elements in the same array. Initially, both pointers are set to the beginning of the array. The algorithm then iterates through the array, comparing the current element with the previous element. If the current element is not equal to the previous element, it means that the current element is unique, and it is stored in the array using the second pointer. The second pointer is then incremented, and the process continues until all elements have been processed. Once the iteration is complete, the new length of the modified array, as indicated by the second pointer, is returned. The unique elements are now stored in the first few positions of the original array, and the remaining positions may contain leftover duplicate elements which can be ignored.
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0) return 0;
int low = 0;
for (int high = 1; high < n; high++) {
if (A[low] != A[high])
A[++low] = A[high];
}
return low + 1;
}
};