Saturday, 11 November 2017

C++ Program to find the smallest index of the repeated element.

Question:-

Find the first index of the repeated element in an array of integers, i.e., an element that occurs more than once and whose index of first occurrence is smallest. 

Use 1 based indexing.

Example:-

Let arr={1 5 3 4 3 5 6}
Output: 2 because 5 is appearing twice and its first appearance is at index 2 which is less than 3 whose first occuring index is 3.


PROGRAM:


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
  //code
  int t;
  cout<<"\nEnter the number of test cases: \n";
  cin>>t;
  while(t--){

       cout<<"\nEnter the total number of  elements: \n";
       int n;
       cin>>n;
       std::unordered_map<int,int> m1;
       std::unordered_map<int,int> m2;
       int num;

       cout<<"\nEnter the elements of the array: \n";
       for(int i=0;i<n;i++){
           cin>>num;
           m1[num]++;
           if(m1[num]==1){
               m2[num]=i;
           }
           
       }
       int flag=0;
       int result=INT_MAX;
       for(auto it=m2.begin();it!=m2.end();it++){
             if(m1[it->first]>1){
                  if(result>m2[it->first]){
                      result=m2[it->first];
                      flag=1;
                  }
             }
       }
       if(flag){ 
                
                cout<<"\n\nThe smallest index of the repeated element is:\n ";
                cout<<result+1;
       }
       else cout<<"\n\nThere is no repeated element in the array\n";
       cout<<"\n";
  }
  return 0;
}


OUTPUT:





EmoticonEmoticon