C++ Program for Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message.
Examples:
Input : arr[] = {1, 5, 5, 6, 6, 7}
Output :
Last index: 4
Last duplicate item: 6
Input : arr[] = {1, 2, 3, 4, 5}
Output : No duplicate found
We simply iterate through the array in reverse order and compare the current and previous element. If a match is found then we print the index and duplicate element. As this is sorted array it will be the last duplicate. If no such element is found we will print the message for it.
1- for i = n-1 to 0
if (arr[i] == arr[i-1])
Print current element and its index.
Return
2- If no such element found print a message
of no duplicate found.
C++
#include <bits/stdc++.h>
void dupLastIndex( int arr[], int n) {
if (arr == NULL || n <= 0)
return ;
for ( int i = n - 1; i > 0; i--) {
if (arr[i] == arr[i - 1]) {
printf ("Last index: %d
Last "
"duplicate item: %d
", i, arr[i]);
return ;
}
}
printf ( "no duplicate found" );
}
int main() {
int arr[] = {1, 5, 5, 6, 6, 7, 9};
int n = sizeof (arr) / sizeof ( int );
dupLastIndex(arr, n);
return 0;
}
|
Output:
Last index: 4
Last duplicate item: 6
Time Complexity: O(n), where n represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Last duplicate element in a sorted array for more details!
Last Updated :
09 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...