Find the first repeating element in an array of integers - GeeksforGeeks

10 Feb, 2022
Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest. 
Examples: 
Input:  arr[] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 [5 is the first element that repeats]

Input:  arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
Output: 6 [6 is the first element that repeats]
A Simple Solution is to use two nested loops. The outer loop picks an element one by one, the inner loop checks whether the element is repeated or not. Once we find an element that repeats, we break the loops and print the element. Time Complexity of this solution is O(n2)
We can Use Sorting to solve the problem in O(nLogn) time. Following are detailed steps. 1) Copy the given array to an auxiliary array temp[]. 2) Sort the temp array using a O(nLogn) time sorting algorithm. 3) Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find an element that occurs more than once, we return the element. This step can be done in O(nLogn) time.We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from right to left and update the minimum index whenever we find an element that has been visited on right side. Thanks to Mohammad Shahid for suggesting this solution.
Following is the implementation of this idea.
C++
Java
Python3
C#
Javascript
/* C++ program to find first repeating element in arr[] */#include<bits/stdc++.h>using namespace std; // This function prints the first repeating element in arr[]void printFirstRepeating(int arr[], int n){    // Initialize index of first repeating element    int min = -1;     // Creates an empty hashset    set<int> myset;     // Traverse the input array from right to left    for (int i = n - 1; i >= 0; i--)    {        // If element is already in hash set, update min        if (myset.find(arr[i]) != myset.end())            min = i;         else   // Else add element to hash set            myset.insert(arr[i]);    }     // Print the result    if (min != -1)        cout << "The first repeating element is " << arr[min];    else        cout << "There are no repeating elements";} // Driver method to test above methodint main(){    int arr[] = {10, 5, 3, 4, 3, 5, 6};     int n = sizeof(arr) / sizeof(arr[0]);    printFirstRepeating(arr, n);}//This article is contributed by Chhavi
/* 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);    }}
# Python3 program to find first repeating# element in arr[] # This function prints the first repeating# element in arr[]def printFirstRepeating(arr, n):     # Initialize index of first repeating element    Min = -1     # Creates an empty hashset    myset = dict()     # Traverse the input array from right to left    for i in range(n - 1, -1, -1):             # If element is already in hash set,        # update Min        if arr[i] in myset.keys():            Min = i         else: # Else add element to hash set            myset[arr[i]] = 1         # Print the result    if (Min != -1):        print("The first repeating element is",                                      arr[Min])    else:        print("There are no repeating elements") # Driver Codearr = [10, 5, 3, 4, 3, 5, 6] n = len(arr)printFirstRepeating(arr, n) # This code is contributed by Mohit kumar 29
using System;using System.Collections.Generic; /* C# program to find first repeating element in arr[] */ public class GFG{    // This function prints the first repeating element in arr[]    public static void printFirstRepeating(int[] arr)    {        // Initialize index of first repeating element        int min = -1;         // Creates an empty hashset        HashSet<int> set = new HashSet<int>();         // 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)        {          Console.WriteLine("The first repeating element is " + arr[min]);        }        else        {          Console.WriteLine("There are no repeating elements");        }    }     // Driver method to test above method     public static void Main(string[] args)    {        int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6};        printFirstRepeating(arr);    }} // This code is contributed by Shrikant13
<script> // Javascript program to find first// repeating element in arr[]     // This function prints the first// repeating element in arr[]function  printFirstRepeating(arr){         // Initialize index of first    // repeating element    let min = -1;     // Creates an empty hashset    let set = new Set();     // Traverse the input array from right to left    for(let i = arr.length - 1; i >= 0; i--)    {                 // If element is already in        // hash set, update min        if (set.has(arr[i]))            min = i;                     // Else add element to hash set        else             set.add(arr[i]);    }     // Print the result    if (min != -1)      document.write("The first repeating element is " +                     arr[min]);    else      document.write("There are no repeating elements");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ]; printFirstRepeating(arr); // This code is contributed by unknown2108     </script>
  
The first repeating element is 5
 
Another Approach:If you want to do this without using any additional data structure. The problem can also be solved using array only. See the method below. 
 
C++
Java
Python3
C#
Javascript
/* C++ program to find firstrepeating element in arr[] */#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]void printFirstRepeating(int arr[], int n){         // This will set k=1, if any    // repeating element found    int k = 0;     // max = maximum from (all elements & n)    int max = n;    for (int i = 0; i < n; i++)        if (max < arr[i])            max = arr[i];     // Array a is for storing    // 1st time occurrence of element    // initialized by 0    int a[max + 1] = {};     // Store 1 in array b    // if element is duplicate    // initialized by 0    int b[max + 1] = {};     for (int i = 0; i < n; i++)    {             // Duplicate element found        if (a[arr[i]])        {            b[arr[i]] = 1;            k = 1;            continue;        }        else            // storing 1st occurrence of arr[i]            a[arr[i]] = i+1;    }     if (k == 0)        cout << "No repeating element found" << endl;    else    {        int min = max + 1;               // trace array a & find repeating element        // with min index        for (int i = 0; i < max + 1; i++)            if (a[i] && min > a[i] && b[i])                min = a[i];        cout << arr[min-1];    }    cout << endl;} // Driver method to test above methodint main(){    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };     int n = sizeof(arr) / sizeof(arr[0]);    printFirstRepeating(arr, n);}
/* Java program to find firstrepeating element in arr[] */public class GFG{   // This function prints the  // first repeating element in arr[]  static void printFirstRepeating(int[] arr, int n)  {     // This will set k=1, if any    // repeating element found    int k = 0;     // max = maximum from (all elements & n)    int max = n;    for (int i = 0; i < n; i++)      if (max < arr[i])        max = arr[i];     // Array a is for storing    // 1st time occurrence of element    // initialized by 0    int[] a = new int[max + 1];     // Store 1 in array b    // if element is duplicate    // initialized by 0    int[] b = new int[max + 1];    for (int i = 0; i < n; i++)    {       // Duplicate element found      if (a[arr[i]] != 0)      {        b[arr[i]] = 1;        k = 1;        continue;      }      else        // storing 1st occurrence of arr[i]        a[arr[i]] = i+1;    }     if (k == 0)      System.out.println("No repeating element found");    else    {      int min = max + 1;       // trace array a & find repeating element      // with min index      for (int i = 0; i < max + 1; i++)        if (a[i] != 0 && min > a[i] && b[i] != 0)          min = a[i];      System.out.print(arr[min-1]);    }    System.out.println();  }   // Driver code  public static void main(String[] args)  {    int[] arr = { 10, 5, 3, 4, 3, 5, 6 };     int n = arr.length;    printFirstRepeating(arr, n);  }} // This code is contributed by divyesh072019
# Python3 program to find first # repeating element in arr[] # This function prints the # first repeating element in arr[]def printFirstRepeating(arr, n):         # This will set k=1, if any     # repeating element found    k = 0     # max = maximum from (all elements & n)    max = n         for i in range(n):        if (max < arr[i]):            max = arr[i]         # Array a is for storing     # 1st time occurrence of element    # initialized by 0    a = [0 for i in range(max + 1)]     # Store 1 in array b     # if element is duplicate    # initialized by 0    b = [0 for i in range(max + 1)]     for i in range(n):         # Duplicate element found        if (a[arr[i]]):            b[arr[i]] = 1            k = 1            continue        else:             # Storing 1st occurrence of arr[i]            a[arr[i]] = i+1     if (k == 0):        print("No repeating element found")    else:        min = max + 1         for i in range(max + 1):                         # Trace array a & find repeating            # element with min index            if (a[i] and (min > (a[i])) and b[i]):                min = a[i]                         print(arr[min-1]) # Driver codearr = [ 10, 5, 3, 4, 3, 5, 6 ]n = len(arr) printFirstRepeating(arr, n) # This code is contributed by avanitrachhadiya2155
/* C# program to find firstrepeating element in arr[] */using System;class GFG{         // This function prints the    // first repeating element in arr[]    static void printFirstRepeating(int[] arr, int n)    {                  // This will set k=1, if any        // repeating element found        int k = 0;              // max = maximum from (all elements & n)        int max = n;        for (int i = 0; i < n; i++)            if (max < arr[i])                max = arr[i];              // Array a is for storing        // 1st time occurrence of element        // initialized by 0        int[] a = new int[max + 1];              // Store 1 in array b        // if element is duplicate        // initialized by 0        int[] b = new int[max + 1];              for (int i = 0; i < n; i++)        {                      // Duplicate element found            if (a[arr[i]] != 0)            {                b[arr[i]] = 1;                k = 1;                continue;            }            else                // storing 1st occurrence of arr[i]                a[arr[i]] = i+1;        }              if (k == 0)            Console.WriteLine("No repeating element found");        else        {            int min = max + 1;                        // trace array a & find repeating element            // with min index            for (int i = 0; i < max + 1; i++)                if ((a[i] != 0) && min > a[i] && (b[i] != 0))                    min = a[i];            Console.Write(arr[min-1]);        }        Console.WriteLine();    }   // Driver code  static void Main()  {    int[] arr = { 10, 5, 3, 4, 3, 5, 6 };      int n = arr.Length;    printFirstRepeating(arr, n);  }} // This code is contributed by divyeshrabadiya07.
<script>/* javascript program to find firstrepeating element in arr */       // This function prints the    // first repeating element in arr    function printFirstRepeating(arr , n) {         // This will set k=1, if any        // repeating element found        var k = 0;         // max = maximum from (all elements & n)        var max = n;        for (i = 0; i < n; i++)            if (max < arr[i])                max = arr[i];         // Array a is for storing        // 1st time occurrence of element        // initialized by 0        var a = Array(max + 1).fill(0);         // Store 1 in array b        // if element is duplicate        // initialized by 0        var b = Array(max + 1).fill(0);        for (var i = 0; i < n; i++) {             // Duplicate element found            if (a[arr[i]] != 0) {                b[arr[i]] = 1;                k = 1;                continue;            } else                // storing 1st occurrence of arr[i]                a[arr[i]] = i+1;        }         if (k == 0)            document.write("No repeating element found");        else {            var min = max + 1;             // trace array a & find repeating element            // with min index            for (i = 0; i < max + 1; i++)                if (a[i] != 0 && min > a[i] && b[i] != 0)                    min = a[i];            document.write(arr[min-1]);        }        document.write("<br/>");    }     // Driver code             var arr = [ 10, 5, 3, 4, 3, 5, 6 ];         var n = arr.length;        printFirstRepeating(arr, n); // This code is contributed by todaysgaurav</script>
5
Time Complexity: O(n).
Another Approach By Using O(n) Auxiliary Space and O(n) Time Complexity:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;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[max + 1];     for (int i = 0; i < max + 1; i++)        temp[i] = 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}int main(){     int arr[] = { 10, 5, 3, 4, 3, 5, 6 };     int n = sizeof(arr) / sizeof(arr[0]);    int index = firstRepeated(        arr, n); // index Of 1st repeating number    if (index != -1) {        cout << "1st Repeating Number is  " << arr[index];    }    else {        cout << "No Repeating Number Found";    }     return 0;} // This code is contributed by gauravrajput1
/*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");        }    }}
def firstRepeated(arr, n):    max = 0;    for x in range(n):        if (arr[x] > max):            max = arr[x];         temp = [0 for i in range(max + 1)]; # the idea is to use                                    # temporary array as hashmap    # Arrays.fill(temp, 0);     for x in range(n):        num = arr[x];        temp[num]+=1;         for x in range(n):        num = arr[x];        if (temp[num] > 1):            return x;             return -1; # if no repeating element found if __name__ == '__main__':    arr = [ 10, 5, 3, 4, 3, 5, 6 ];     n = len(arr);    index = firstRepeated(arr, len(arr)); # index Of 1st repeating number    if (index != -1):        print("1st Repeating Number is ", arr[index]);    else:        print("No Repeating Number Found");     # This code is contributed by gauravrajput1
/*package whatever //do not write package name here */using System;using System.Collections.Generic;public 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      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  }   // Driver code  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) {      Console.WriteLine("1st Repeating Number is  "                        + arr[index]);    }    else {      Console.WriteLine("No Repeating Number Found");    }  }} // This code is contributed by gauravrajput1
<script> function firstRepeated(arr, n)    {        var max = 0;        for (var x = 0; x < n; x++) {            if (arr[x] > max) {                max = arr[x];            }        }        var temp            = new Array(max + 1); // the idea is to use                                // temporary array as hashmap       // Arrays.fill(temp, 0);         for (var x = 0; x < n; x++) {            var num = arr[x];            temp[num]++;        }         for (var x = 0; x < n; x++) {            var num = arr[x];            if (temp[num] > 1) {                return x;            }        }         return -1; // if no repeating element found    }            var arr = [ 10, 5, 3, 4, 3, 5, 6 ];         var n = arr.length;        var index = firstRepeated(            arr,            arr.length); // index Of 1st repeating number        if (index = 1) {           document.write("1st Repeating Number is  "                               + arr[index]);        }        else {           document.write("No Repeating Number Found");      } // This code is contributed by shivanisinghss2110</script>
Another Approach Using Python inbuilt functions: 
C++
Java
Python3
C#
Javascript
// C++ program to find first// repeating element in arr[]#include <bits/stdc++.h>using namespace std; // This function prints the// first repeating element in arr[]string printFirstRepeating(vector<int> a) {  for (int i = 0; i < a.size(); i++) {    if (count(a.begin(), a.end(), a[i]) > 1)      return to_string(a[i]);  }  return "there is no repetition number";} int main(){   // Driver code  std::vector<int> arr{ 10, 5, 3, 4, 3, 5, 6 };   cout<<(printFirstRepeating(arr));  return 0;} // This code is contributed by Rajput-Ji
import java.util.Arrays;import java.util.Collections;import java.util.List; // Java program to find first// repeating element in arr[]class GFG{       // This function prints the    // first repeating element in arr[]    static String printFirstRepeating(List<Integer> a) {        for (int i = 0; i < a.size(); i++) {            if (Collections.frequency(a, a.get(i)) > 1)                return String.valueOf(a.get(i));        }        return "there is no repetition number";    }     public static void main(String[] args) {         // Driver code        Integer[] arr = { 10, 5, 3, 4, 3, 5, 6 };         System.out.println(printFirstRepeating(Arrays.asList(arr)));    }} // This code is contributed by shikhasingrajput
# Python3 program to find first# repeating element in arr[] # This function prints the# first repeating element in arr[]def printFirstRepeating(a, n):    for i in range(len(a)):        if a.count(a[i]) > 1:            return a[i]    return "there is no repetition number"  # Driver codearr = [10, 5, 3, 4, 3, 5, 6]n = len(arr)print(printFirstRepeating(arr, n)) # This code is contributed by karthikeyakumarnallam
// C# program to find first// repeating element in arr[]using System;using System.Collections.Generic;class GFG{   // This function prints the first  // repeating element in arr[]  static void printFirstRepeating(int[] arr, int n)  {     // Initialize index of first    // repeating element    int min = -1;     // Creates an empty hashset    HashSet<int> set = new HashSet<int>();     // Traverse the input array from right to left    for (int i = n - 1; i >= 0; i--)    {       // If element is already in      // hash set, update min      if (set.Contains(arr[i]))        min = i;       // Else add element to hash set      else        set.Add(arr[i]);    }     // Print the result    if (min != -1)      Console.Write(arr[min]);    else      Console.Write("there is no repetition number");  }   // Driver code  public static void Main()  {    int[] arr = { 10, 5, 3, 4, 3, 5, 6 };    int n = arr.Length;     printFirstRepeating(arr, n);  } } // This code is contributed by gfgking
<script> // Javascript program to find first// repeating element in arr[]     // This function prints the first// repeating element in arr[]function printFirstRepeating(arr, n){         // Initialize index of first    // repeating element    let min = -1;     // Creates an empty hashset    let set = new Set();     // Traverse the input array from right to left    for(let i = n - 1; i >= 0; i--)    {                 // If element is already in        // hash set, update min        if (set.has(arr[i]))            min = i;                     // Else add element to hash set        else            set.add(arr[i]);    }     // Print the result    if (min != -1)    document.write(arr[min]);    else    document.write("there is no repetition number");} // Driver codelet arr = [ 10, 5, 3, 4, 3, 5, 6 ];let n = arr.length; printFirstRepeating(arr, n); // This code is contributed by splevel62.</script>
5
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
mohit kumar 29
rampaliwal49
avanitrachhadiya2155
karthikeyakumarnallam
divyeshrabadiya07
divyesh072019
sarthak8858
unknown2108
todaysgaurav
surindertarika1234
khushboogoyal499
GauravRajput1
simmytarika5
shivanisinghss2110
splevel62
shikhasingrajput
gfgking
Rajput-Ji
Amazon
Oracle
Arrays
Hash
Searching
Amazon
Oracle
Arrays
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)