xxxxxxxxxx
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static int firstRepeated(int[] arr, int n)
{
int max = 0;
for (int x = 0; x < n; x++) {
if (arr[x] > max) {
max = arr[x];
}
}
int temp[]
= new int[max + 1]; // the idea is to use
// temporary array as hashmap
// Arrays.fill(temp, 0);
for (int x = 0; x < n; x++) {
int num = arr[x];
temp[num]++;
}
for (int x = 0; x < n; x++) {
int num = arr[x];
if (temp[num] > 1) {
return x;
}
}
return -1; // if no repeating element found
}
public static void main(String[] args)
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.length;
int index = firstRepeated(
arr,
arr.length); // index Of 1st repeating number
if (index != -1) {
System.out.println("1st Repeating Number is "
+ arr[index]);
}
else {
System.out.println("No Repeating Number Found");
}
}
}
xxxxxxxxxx
/* Java program to find first repeating element in arr[] */
import java.util.*;
class Main
{
// This function prints the first repeating element in arr[]
static void printFirstRepeating(int arr[])
{
// Initialize index of first repeating element
int min = -1;
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Traverse the input array from right to left
for (int i=arr.length-1; i>=0; i--)
{
// If element is already in hash set, update min
if (set.contains(arr[i]))
min = i;
else // Else add element to hash set
set.add(arr[i]);
}
// Print the result
if (min != -1)
System.out.println("The first repeating element is " + arr[min]);
else
System.out.println("There are no repeating elements");
}
// Driver method to test above method
public static void main (String[] args) throws java.lang.Exception
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
printFirstRepeating(arr);
}
}