Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmPython Program for Last duplicate element in a sorted array

Python 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.

 

Python3




# Python3 code to print last duplicate
# element and its index in a sorted array
 
def dupLastIndex(arr, n):
 
    # if array is null or size is less
    # than equal to 0 return
    if (arr == None or n <= 0):
        return
 
    # compare elements and return last
    # duplicate and its index
    for i in range(n - 1, 0, -1):
         
        if (arr[i] == arr[i - 1]):
            print("Last index:", i, "
Last",
                     "duplicate item:",arr[i])
            return
         
    # If we reach here, then no duplicate
    # found.
    print("no duplicate found")
     
 
arr = [1, 5, 5, 6, 6, 7, 9]
n = len(arr)
dupLastIndex(arr, n)
 
# This code is contributed by
# Smitha Dinesh Semwal


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments