![]() |
VOOZH | about |
In this article, we will learn how to remove duplicates from a sorted array using the C program.
Input: arr[] = [2, 4, 4, 4, 6]
Output: [2, 4, 6]
Explanation : There are only 3 unique elements - {2, 4, 6}.Input: arr[] = [1, 1, 2, 3, 3, 4, 4, 5]
Output : [1, 2, 3, 4, 5]
Explanation : There are only 5 unique elements - {1, 2, 3, 4, 5}.
Table of Content
The most straightforward method is to use the two-pointer approach which uses two pointers: one pointer to iterate over the array and other to track duplicate elements. In sorted arrays, duplicates are adjacent, so just check the adjacent elements replace them with first non-duplicate.
1 2 3 4 5
Explanation: In this program, the new end is returned because we cannot actually delete an element from the static array in C. So, a pointer to the end is created to represent the logical end.
There are also a few other methods in C to remove duplicates from a sorted array. Some of them are as follows:
This method uses a temporary frequency array to track whether an element has already been encountered, and then reconstructs the array using only the first occurrence of each element.
1 2 3 4 5
If the original array must not be modified, instead of pointing j to the current array, point j to the new array and insert unique element to this new array using either the two-pointer approach or frequency counting.
1 2 3 4 5