Find repeated character present first in a string - GeeksforGeeks

14 Feb, 2022
Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) 
Examples: 
Input  : geeksforgeeks
Output : g
(mind that it will be g, not e.)
Asked in: Goldman Sachs internship 
Simple Solution using O(N^2) complexity The solution is to loop through the string for each character and search for the same in the rest of the string. This would need two loops and thus not optimal.  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find the first// character that is repeated#include <bits/stdc++.h>#include <string.h> using namespace std;int findRepeatFirstN2(char* s){    // this is O(N^2) method    int p = -1, i, j;    for (i = 0; i < strlen(s); i++)    {        for (j = i + 1; j < strlen(s); j++)        {            if (s[i] == s[j])            {                p = i;                break;            }        }        if (p != -1)            break;    }     return p;} // Driver codeint main(){    char str[] = "geeksforgeeks";    int pos = findRepeatFirstN2(str);    if (pos == -1)        cout << "Not found";    else        cout << str[pos];    return 0;} // This code is contributed// by Akanksha Rai
// C program to find the first character that// is repeated#include <stdio.h>#include <string.h> int findRepeatFirstN2(char* s){    // this is O(N^2) method    int p = -1, i, j;    for (i = 0; i < strlen(s); i++) {        for (j = i + 1; j < strlen(s); j++) {            if (s[i] == s[j]) {                p = i;                break;            }        }        if (p != -1)            break;    }     return p;} // Driver codeint main(){    char str[] = "geeksforgeeks";    int pos = findRepeatFirstN2(str);    if (pos == -1)        printf("Not found");    else        printf("%c", str[pos]);    return 0;}
// Java program to find the first character// that is repeatedimport java.io.*;import java.util.*; class GFG {     static int findRepeatFirstN2(String s)    {                 // this is O(N^2) method        int p = -1, i, j;        for (i = 0; i < s.length(); i++)        {            for (j = i + 1; j < s.length(); j++)            {                if (s.charAt(i) == s.charAt(j))                {                    p = i;                    break;                }            }            if (p != -1)                break;        }             return p;    }         // Driver code    static public void main (String[] args)    {        String str = "geeksforgeeks";        int pos = findRepeatFirstN2(str);                 if (pos == -1)            System.out.println("Not found");        else        System.out.println( str.charAt(pos));    }} // This code is contributed by anuj_67.
# Python3 program to find the first# character that is repeated def findRepeatFirstN2(s):     # this is O(N^2) method    p = -1    for i in range(len(s)):             for j in range (i + 1, len(s)):                     if (s[i] == s[j]):                p = i                break                     if (p != -1):            break     return p # Driver codeif __name__ == "__main__":     str = "geeksforgeeks"    pos = findRepeatFirstN2(str)    if (pos == -1):        print ("Not found")    else:        print (str[pos])     # This code is contributed# by ChitraNayal
// C# program to find the first character// that is repeatedusing System; class GFG {     static int findRepeatFirstN2(string s)    {                 // this is O(N^2) method        int p = -1, i, j;        for (i = 0; i < s.Length; i++)        {            for (j = i + 1; j < s.Length; j++)            {                if (s[i] == s[j])                {                    p = i;                    break;                }            }            if (p != -1)                break;        }             return p;    }         // Driver code    static public void Main ()    {        string str = "geeksforgeeks";        int pos = findRepeatFirstN2(str);                 if (pos == -1)            Console.WriteLine("Not found");        else        Console.WriteLine( str[pos]);    }} // This code is contributed by anuj_67.
<?php// PHP program to find the first// character that is repeated function findRepeatFirstN2($s){    // this is O(N^2) method    $p = -1;    for ($i = 0; $i < strlen($s); $i++)    {        for ($j = ($i + 1);             $j < strlen($s); $j++)        {            if ($s[$i] == $s[$j])            {                $p = $i;                break;            }        }        if ($p != -1)            break;    }     return $p;} // Driver code$str = "geeksforgeeks";$pos = findRepeatFirstN2($str); if ($pos == -1)    echo ("Not found");else    echo ($str[$pos]); // This code is contributed by jit_t?>
<script> // Javascript program to find the first// character that is repeatedfunction findRepeatFirstN2(s){         // This is O(N^2) method    let p = -1, i, j;    for(i = 0; i < s.length; i++)    {        for(j = i + 1; j < s.length; j++)        {            if (s[i] == s[j])            {                p = i;                break;            }        }        if (p != -1)            break;    }    return p;} // Driver codelet str = "geeksforgeeks";let pos = findRepeatFirstN2(str); if (pos == -1)    document.write("Not found");else    document.write(str[pos]);     // This code is contributed by suresh07   </script>
g
Optimization by counting occurrencesThis solution is optimized by using the following techniques: 1. We loop through the string and hash the characters using ASCII codes. Store 1 if found and store 2 if found again. Also, store the position of the letter first found in.2. We run a loop on the hash array and now we find the minimum position of any character repeated.
This will have a runtime of O(N).
C++
C
Java
Python3
C#
Javascript
// C++ program to find the first character that// is repeated#include<bits/stdc++.h> using namespace std;// 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){    // this is optimized method    int p = -1, i, k;     // initialized counts of occurrences of    // elements as zero    int hash[MAX_CHAR] = { 0 };     // initialized positions    int pos[MAX_CHAR];     for (i = 0; i < strlen(s); i++) {        k = (int)s[i];        if (hash[k] == 0) {            hash[k]++;            pos[k] = i;        } else if (hash[k] == 1)            hash[k]++;    }     for (i = 0; i < MAX_CHAR; i++) {        if (hash[i] == 2) {            if (p == -1) // base case                p = pos[i];            else if (p > pos[i])                p = pos[i];        }    }     return p;} // Driver codeint main(){    char str[] = "geeksforgeeks";    int pos = findRepeatFirst(str);    if (pos == -1)        cout << "Not found";    else        cout << str[pos];    return 0;} // This code is contributed// by Akanksha Rai
// C program to find the first character that// is repeated#include <stdio.h>#include <string.h> // 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){    // this is optimized method    int p = -1, i, k;     // initialized counts of occurrences of    // elements as zero    int hash[MAX_CHAR] = { 0 };     // initialized positions    int pos[MAX_CHAR];     for (i = 0; i < strlen(s); i++) {        k = (int)s[i];        if (hash[k] == 0) {            hash[k]++;            pos[k] = i;        } else if (hash[k] == 1)            hash[k]++;    }     for (i = 0; i < MAX_CHAR; i++) {        if (hash[i] == 2) {            if (p == -1) // base case                p = pos[i];            else if (p > pos[i])                p = pos[i];        }    }     return p;} // Driver codeint main(){    char str[] = "geeksforgeeks";    int pos = findRepeatFirst(str);    if (pos == -1)        printf("Not found");    else        printf("%c", str[pos]);    return 0;}
// Java Program to find the first character // that is repeated import java.util.*;import java.lang.*; public class GFG{    public static int findRepeatFirst(String s)    {        // this is optimized method        int p = -1, i, k;         // initialized counts of occurrences of        // elements as zero        int MAX_CHAR = 256;        int hash[] = new int[MAX_CHAR];         // initialized positions        int pos[] = new int[MAX_CHAR];         for (i = 0; i < s.length(); i++)        {            k = (int)s.charAt(i);            if (hash[k] == 0)            {                hash[k]++;                pos[k] = i;            }            else if (hash[k] == 1)                hash[k]++;        }         for (i = 0; i < MAX_CHAR; i++)        {            if (hash[i] == 2)            {                if (p == -1) // base case                    p = pos[i];                else if (p > pos[i])                    p = pos[i];            }        }         return p;    } // Driver code    public static void main(String[] args)    {        String str = "geeksforgeeks";        int pos = findRepeatFirst(str);        if (pos == -1)            System.out.println("Not found");        else            System.out.println(str.charAt(pos));    }} // Code Contributed by Mohit Gupta_OMG
# Python 3 program to find the first# character that is repeated # 256 is taken just to ensure nothing# is left, actual max ASCII limit is 128 MAX_CHAR = 256 def findRepeatFirst(s):         # this is optimized method    p = -1     # initialized counts of occurrences    # of elements as zero    hash = [0 for i in range(MAX_CHAR)]     # initialized positions    pos = [0 for i in range(MAX_CHAR)]     for i in range(len(s)):        k = ord(s[i])        if (hash[k] == 0):            hash[k] += 1            pos[k] = i        elif(hash[k] == 1):            hash[k] += 1     for i in range(MAX_CHAR):        if (hash[i] == 2):            if (p == -1): # base case                p = pos[i]            elif(p > pos[i]):                p = pos[i]    return p # Driver codeif __name__ == '__main__':    str = "geeksforgeeks"    pos = findRepeatFirst(str);    if (pos == -1):        print("Not found")    else:        print(str[pos])         # This code is contributed by# Shashank_Sharma
// C# Program to find the first character // that is repeatedusing System;public class GFG{    public static int findRepeatFirst(string s)    {        // this is optimized method        int p = -1, i, k;          // initialized counts of occurrences of        // elements as zero        int MAX_CHAR = 256;        int []hash = new int[MAX_CHAR];          // initialized positions        int []pos = new int[MAX_CHAR];          for (i = 0; i < s.Length; i++)        {            k = (int)s[i];            if (hash[k] == 0)            {                hash[k]++;                pos[k] = i;            }            else if (hash[k] == 1)                hash[k]++;        }          for (i = 0; i < MAX_CHAR; i++)        {            if (hash[i] == 2)            {                if (p == -1) // base case                    p = pos[i];                else if (p > pos[i])                    p = pos[i];            }        }          return p;    }      // Driver code    public static void Main()    {        string str = "geeksforgeeks";        int pos = findRepeatFirst(str);        if (pos == -1)            Console.Write("Not found");        else            Console.Write(str[pos]);    }}  // This code is contributed by nitin mittal.
<script>    // Javascript Program to find the first character that is repeated         function findRepeatFirst(s)    {        // this is optimized method        let p = -1, i, k;           // initialized counts of occurrences of        // elements as zero        let MAX_CHAR = 256;        let hash = new Array(MAX_CHAR);        hash.fill(0);           // initialized positions        let pos = new Array(MAX_CHAR);        pos.fill(0);           for (i = 0; i < s.length; i++)        {            k = s[i].charCodeAt();            if (hash[k] == 0)            {                hash[k]++;                pos[k] = i;            }            else if (hash[k] == 1)                hash[k]++;        }           for (i = 0; i < MAX_CHAR; i++)        {            if (hash[i] == 2)            {                if (p == -1) // base case                    p = pos[i];                else if (p > pos[i])                    p = pos[i];            }        }           return p;    }         let str = "geeksforgeeks";    let pos = findRepeatFirst(str);    if (pos == -1)      document.write("Not found");    else      document.write(str[pos]); // This code is contributed by rameshtravel07.</script>
g
Calculate all frequencies of all characters using Counter() function.
Traverse the string and check if any element has frequency greater than 1.
Print the character and break the  loop
Below is the implementation:
Python3
# Python implementationfrom collections import Counter # Function which repeats# first repeating characterdef printrepeated(string):       # Calculating frequencies    # using Counter function    freq = Counter(string)         # Traverse the string    for i in string:        if(freq[i] > 1):            print(i)            break  # Driver codestring = "geeksforgeeks" # passing string to printrepeated functionprintrepeated(string) # this code is contributed by vikkycirus
g
Time Complexity:O(n)
Space Complexity:O(n)
Method #4: Solving just by single traversal of the given string.
Algorithm :
1. Traverse the string from left to right.
2. If current character is not present in hash map, Then push this character along with its Index.
3. If the current character is already present in hash map, Then get the index of current character ( from hash map ) and compare it with the index of the previously found repeating character.
4. If the current index is smaller, then update the index.
C++
Javascript
#include <iostream>#include<unordered_map>#define INT_MAX 2147483647using namespace std; // Function to find left most repeating character.char firstRep (string s)    {        unordered_map<char,int> map;        char c='#';        int index=INT_MAX;                 // single traversal of string.        for(int i=0;i<s.size();i++)        {            char p=s[i];                         if(map.find(p)==map.end())map.insert({p,i});            else            {                if(map[p]<index)                {                    index=map[p];                    c=p;                }            }                     }                          return c;    } // Main function.int main() {     // Input string.    string s="abccdbd";    cout<<firstRep(s)<<endl;         return 0;}  // This code is contributed// by rohan007
<script>// JavaScript code to find the first repeating character in a stringconst INT_MAX = 2147483647 // Function to find left most repeating character.function firstRep(s){    map = new Map();    let c = '#';    let index=INT_MAX;             // single traversal of string.    for(let i = 0; i < s.length; i++)    {        let p = s[i];                     if(!map.has(p))map.set(p,i);        else        {            if(map.get(p) < index)            {                index = map.get(p);                c = p;            }        }            }    return c;} // Driver code // Input string.const s="abccdbd";document.write(firstRep(s));     // This code is contributed by shinjanpatra</script>
b
Time complexity:    O(N)
Space complexity:  O(N)
More optimized Solution Repeated Character Whose First Appearance is LeftmostThis article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
vt_m
jit_t
Akanksha_Rai
ukasp
Shashank_Sharma
vikkycirus
suresh07
rameshtravel07
rohan007
arorakashish0911
shinjanpatra
Goldman Sachs
Strings
Goldman Sachs
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
Convert string to char array in C++
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters