In this tutorial, we will learn to find the first repeating element in an array of integers in Java.
This type of question can be asked in your placement drives. So now we will have a deep discussion on it with easy examples.
Problem Statement
There will be a given array and we must find its first repeating element. So basically we need to find the element that occurs often and the index of the first occurrence should be the smallest.
Example:
let us consider an array [4,8,6,1,2,5,7,8,6]
so here we can see that 8 is the first repeating number.
Solution Using Nested Loops
To find the solution, we have to use two nested loops. Here, the outer loop will choose the elements one by one and the inner loop will check if any element is repeating or not. If any element is repeated the loops will be broken and the element will get printed.
Time Complexity
The time complexity of the solution will be O(n2).
Code
Now we will see an easy example to find the first repeating element in an array
import java.util.*; public class demo { public static int repeatingelement(int[] arr, int k) { //to check repeating elements, use nested loop for (int i = 0; i < k; i++) { for (int j = i + 1; j < k; j++) { //any repeating element is there, return the index of that element if (arr[i] == arr[j]) { return i; } } } //if there is no repeating element then return -1 return -1; } public static void main(String args[]) { //array initialising int[] array = {8, 5, 6, 4, 8, 1, 5}; int k = array.length; //index of the element which is repeated first int ind = repeatingelement(array, k); //checking for repeated element if (ind == -1) { System.out.println("No repeating element"); } else { //now printing the repeating element and the index of that element System.out.println("The First Repeating element is " + array[ind]); } } }
OUTPUT:
The First Repeating element is 8
There are more methods like hashing and sorting methods. But the nested loops method is efficient.