02 First Repeating Element
Question
Given an array arr[] of size n, find the first repeating element. The element should occur more than once and the index of its first occurrence should be the smallest.
Example 1
Input:
n = 7
arr[] = {1, 5, 3, 4, 3, 5, 6}
Output: 2
Explanation:
5 is appearing twice and
its first appearence is at index 2
which is less than 3 whose first
occuring index is 3.Example 2
Input:
n = 4
arr[] = {1, 2, 3, 4}
Output: -1
Explanation:
All elements appear only once so
the answer is -1.The function firstRepeated() takes arr and n as input parameters and returns the position of the first repeating element. If there is no such element -1 is returned.
1-based indexing is used.
Expected Time Complexity: O(n)
Expected Auxilliary Space: O(n)
Constraints
1≤n≤106
0≤Ai≤106
Naive Approach
Logic
Run two nested loops
For every element from the outer loop
Check all the elements after that element
If the same element is found then return the iterator of the outer loop
If still nothing found then return -1
Using map
Logic
firstRepeating = -1stores the index of the first repeating element.We traverse the array from right to left.
A set
visitedwill store those elements that we have encountered on the right side of the current element.While traversing from right to left
If any element has already been visited
It is a repeating element.
Suppose this is the first occurence of the repeating element.
Update
firstRepeating
Otherwise add it to the visited list
In the end, either we have
-1infirstRepeatingwhich tells that there are no repetitive elements, or we find the index of the repeating element.
Using set
Last updated