Find the first repeating element in an array of integers.
To find the first repeating element in an array of integers, we can iterate through the array and use a HashMap to keep track of the frequency of each element. The first element that has a frequency greater than 1 is the first repeating element.
Here's the Java code:
import java.util.HashMap;
public class FirstRepeatingElement {
public static Integer findFirstRepeatingElement(int[] arr) {
// create a HashMap to keep track of the frequency of each element
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// iterate through the array and update the frequency in the HashMap
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i])) {
// if the element is already in the HashMap, increment its frequency
map.put(arr[i], map.get(arr[i]) + 1);
} else {
// otherwise, add the element to the HashMap with a frequency of 1
map.put(arr[i], 1);
}
}
// iterate through the array again and return the first element that has a frequency greater than 1
for (int i = 0; i < arr.length; i++) {
if (map.get(arr[i]) > 1) {
return arr[i];
}
}
// if no repeating element is found, return null
return null;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5};
Integer firstRepeatingElement = findFirstRepeatingElement(arr);
System.out.println("The first repeating element is: " + firstRepeatingElement);
}
}
In this example, the input array is {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5}
, and the expected output is 5
.
The time complexity of this program is O(n), where n is the length of the input array.
This is because we iterate through the array twice, each iteration taking O(n) time. The first iteration updates the frequency of each element in the HashMap, and the second iteration finds the first element with a frequency greater than 1.
In the worst case, where there are no repeating elements, we will still need to iterate through the entire array once and perform constant-time operations on each element. Therefore, the time complexity is O(n).
The space complexity is also O(n), as we need to store the frequency of each element in the HashMap. The worst-case scenario is when all the elements are distinct, and we need to store n key-value pairs in the HashMap.