VOOZH about

URL: https://www.geeksforgeeks.org/dsa/last-duplicate-element-sorted-array/

⇱ Last duplicate element in a sorted array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Last duplicate element in a sorted array

Last Updated : 1 Jun, 2026

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.

[Naive Approach] Using Linear Scan from Left to Right - O(n) Time O(1) Space

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.


Output
[4, 6]

Time Complexity: O(n)
Auxiliary Space: O(1)

[Expected Approach] Using Linear Scan from Right to Left - O(n) Time O(1) Space

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]

  • Start traversing the array from the end.
  • At index 5, arr[5] = 7 and arr[4] = 6, so no duplicate is found.
  • At index 4, arr[4] = 6 and arr[3] = 6, so a duplicate is found.
  • Return {4, 6} as the index and value of the last duplicate element.

Output: [4, 6]


Output
[4, 6]

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: