Skip to main content

First Repeated Character

Task: Given a string S. Find the first repeated character in it.

Example:
Input:
1
geeksforgeeks
Output:
e // first repeated character and second time occurred character index is smallest.

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.     string s;
  11.     cin>>s;
  12.     map<char,int> m;
  13.     int c=0;
  14.     for(int i=0;i<s.length();i++)
  15.     {
  16.         m[s[i]]++;
  17.         if(m[s[i]]==2)
  18.         {
  19.             cout<<s[i]<<endl;
  20.             c=1;
  21.             break;
  22.         }
  23.     }
  24.     if(c==0)
  25.     {
  26.         cout<<-1<<endl;
  27.     }
  28. }
  29. return 0;
  30. }

Here is the Video: