First Repeating Element

Easy
0/40
0 upvote

Problem statement

You are given an array 'arr' of 'n' integers.

Your task is to find the first repeating element in the array. The "first" repeating element is the one whose first appearance in the array occurs at the smallest index.

If no element is repeated in the array, your function should return -1.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'n', representing the size of the array.

The second line contains 'n' space-separated integers, representing the elements of the array 'arr'.


Output Format:
Print a single integer which is the first repeating element.
If no repeating element is found, print -1.


Note:
The element that repeats and has the minimum index of its first occurrence is the desired answer.
Sample Input 1:
7
10 5 3 4 3 5 6


Sample Output 1:
5


Explanation for Sample 1:
The repeating elements are 5 and 3.
- The first occurrence of 5 is at index 1.
- The first occurrence of 3 is at index 2.
Since index 1 is smaller than index 2, the first repeating element is 5.


Sample Input 2:
5
1 2 3 4 5


Sample Output 2:
-1


Explanation for Sample 2:
There are no repeating elements in the array.


Expected Time Complexity:
The expected time complexity is O(n).


Constraints:
1 <= n <= 10^5
-10^9 <= arr[i] <= 10^9

Time limit: 1 sec
Approaches (1)
First Repeating Element
Time Complexity

The expected time complexity is O(n)

Space Complexity
Code Solution
(100% EXP penalty)
First Repeating Element
Full screen
Console