Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest.
Examples:
Input: arr[] = {10, 5, 3, 4, 3, 5, 6} Output: 5 [5 is the first element that repeats] Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10} Output: 6 [6 is the first element that repeats]
A Simple Solution is to use two nested loops. The outer loop picks an element one by one, the inner loop checks whether the element is repeated or not. Once we find an element that repeats, we break the loops and print the element. Time Complexity of this solution is O(n2)
We can Use Sorting to solve the problem in O(nLogn) time. Following are detailed steps.
1) Copy the given array to an auxiliary array temp[].
2) Sort the temp array using a O(nLogn) time sorting algorithm.
3) Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find an element that occurs more than once, we return the element. This step can be done in O(nLogn) time.
1) Copy the given array to an auxiliary array temp[].
2) Sort the temp array using a O(nLogn) time sorting algorithm.
3) Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find an element that occurs more than once, we return the element. This step can be done in O(nLogn) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from right to left and update the minimum index whenever we find an element that has been visited on right side. Thanks to Mohammad Shahid for suggesting this solution.
Following is Java implementation of this idea.
/* Java program to find first repeating element in arr[] */ import java.util.*; class Main { // This function prints the first repeating element in arr[] static void printFirstRepeating( int arr[]) { // Initialize index of first repeating element int min = - 1 ; // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Traverse the input array from right to left for ( int i=arr.length- 1 ; i>= 0 ; i--) { // If element is already in hash set, update min if (set.contains(arr[i])) min = i; else // Else add element to hash set set.add(arr[i]); } // Print the result if (min != - 1 ) System.out.println( "The first repeating element is " + arr[min]); else System.out.println( "There are no repeating elements" ); } // Driver method to test above method public static void main (String[] args) throws java.lang.Exception { int arr[] = { 10 , 5 , 3 , 4 , 3 , 5 , 6 }; printFirstRepeating(arr); } } |
Output:
The first repeating element is 5
No comments:
Post a Comment