![]() |
VOOZH | about |
Given a sorted array arr[] that may contain duplicate elements. The task is to find the index of the last occurrence of any duplicate element and return the index along with the value of that element. If no duplicate element is found, return [-1, -1].
Examples:
Input: arr[] = [1, 5, 5, 6, 6, 7]
Output: [4, 6]
Explanation: Last duplicate element is 6 having index 4.
Input: arr[] = [1, 2, 3, 4, 5]
Output: [-1, -1]
Explanation: No duplicate elements are present in the array.
Table of Content
The idea is to traverse the sorted array from left to right and compare every element with its next element. Since duplicates appear consecutively in a sorted array, whenever two adjacent elements are equal, store their index and value.
[4, 6]
Time Complexity: O(n)
Auxiliary Space: O(1)
The idea is to traverse the sorted array from right to left and compare every element with its previous element. Since duplicate elements occur consecutively, the first duplicate pair found during this traversal will be the last duplicate.
Let us understand with example:
Input: arr[] = [1, 5, 5, 6, 6, 7]
Output: [4, 6]
[4, 6]
Time Complexity: O(n)
Auxiliary Space: O(1)