Skip to main content

First Repeating Element

Task: Find the first repeating element in given an array of N elements. If it is present then print that index else print -1.

Example:
Input:
1
1 2 2 3 1
Output:

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5.  {
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10.     int n;
  11.     cin>>n;
  12.     int a[n];
  13.     unordered_map<int, int> m;
  14.     for(int i=0;i<n;i++)
  15.     {
  16.         cin>>a[i];
  17.         m[a[i]]++;
  18.     }
  19.     int c=0;
  20.     for(int i=0;i<n;i++)
  21.     {
  22.         if(m[a[i]]>1)
  23.         {
  24.             cout<<i+1<<endl;
  25.             c=1;
  26.             break;
  27.         }
  28.     }
  29.     if(c==0) cout<<-1<<endl;
  30. }
  31. return 0;
  32. }

Here is the Video: