Problem# Given an array of integers, find the first element that repeats (i.e., appears at least twice) and has the smallest index of first occurrence.
Examples# Example 1# 1
2
3
Input: [ 1 , 1 , 3 , 4 , 6 , 7 , 9 ]
Output: 1
Explanation: 1 is the first element that repeats.
Example 2# 1
2
3
Input: [ 7 , 2 , 2 , 3 , 7 ]
Output: 7
Explanation: 7 is the first element that repeats ( appears at index 0 and again at 4 ).
Example 3# 1
2
3
Input: [ 5 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 4 , 4 , 5 , 3 ]
Output: 5
Explanation: 5 is the first element that repeats ( appears at index 0 and again at 11 ).
Similar Problems Solution# Method 1 – Brute Force# Intuition# Check each element and see if it appears again later in the array.
Approach# For each element, scan the rest of the array to see if it repeats. Return the first element that repeats. Complexity# ⏰ Time complexity: O(n²) — Each element may be compared with all others. 🧺 Space complexity: O(1) — No extra space used. Method 2 – HashSet# Intuition# Track seen elements from right to left, so the last updated index is the smallest index of a repeating element.
Approach# Initialize a variable idx = -1 and an empty set. Traverse the array from right to left: If the element is not in the set, add it. If it is in the set, update idx to the current index. After traversal, if idx != -1, return arr[idx]; otherwise, return a suitable message. Code#
Java
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int firstRepeating (int [] arr) {
int idx = - 1;
Set< Integer> seen = new HashSet<> ();
for (int i = arr.length - 1; i >= 0; i-- ) {
if (seen.contains (arr[ i] )) {
idx = i;
} else {
seen.add (arr[ i] );
}
}
return idx != - 1 ? arr[ idx] : - 1;
}
}
1
2
3
4
5
6
7
8
9
10
class Solution :
def first_repeating (self, arr: list[int]) -> int:
idx = - 1
seen = set()
for i in range(len(arr) - 1 , - 1 , - 1 ):
if arr[i] in seen:
idx = i
else :
seen. add(arr[i])
return arr[idx] if idx != - 1 else - 1
Complexity# ⏰ Time complexity: O(n) — Each element is processed once. 🧺 Space complexity: O(n) — Space for the set.