1function firstDuplicate(a) {
2 let data = [];
3
4 for (dup of a) {
5 if (data[dup]) {
6 return dup
7 } else {
8 data[dup] = dup
9 }
10 }
11 return -1
12}
1import java.util.*;
2
3class Main
4{
5 // This function prints the first repeating element in arr[]
6 static void printFirstRepeating(int arr[])
7 {
8 // Initialize index of first repeating element
9 int min = -1;
10
11 // Creates an empty hashset
12 HashSet<Integer> set = new HashSet<>();
13
14 // Traverse the input array from right to left
15 for (int i=arr.length-1; i>=0; i--)
16 {
17 // If element is already in hash set, update min
18 if (set.contains(arr[i]))
19 min = i;
20
21 else // Else add element to hash set
22 set.add(arr[i]);
23 }
24
25 // Print the result
26 if (min != -1)
27 System.out.println("The first repeating element is " + arr[min]);
28 else
29 System.out.println("There are no repeating elements");
30 }
31
32 // Driver method to test above method
33 public static void main (String[] args) throws java.lang.Exception
34 {
35 int arr[] = {10, 5, 3, 4, 3, 5, 6};
36 printFirstRepeating(arr);
37 }
38}