Open In App
Related Articles

Find the first repeated character in a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a string, find the first repeated character in it. We need to find the character that occurs more than once and whose index of second occurrence is smallest. A variation of this question is discussed here.
 

find first repeated character in a string


Examples: 

Input: ch = “geeksforgeeks” 
Output: e 
e is the first element that repeats

Input: str = “hello geeks” 
Output: l 
l is the first element that repeats

Naive Solution

The solution is to run two nested loops. Start traversing from left side. For every character, check if it repeats or not. If the character repeats, then if the index where it repeated is less than the index of the previously repeated character then store this character and its index where it repeated.
In last print that stored character.

Code to implement the above approach:

C++

// CPP program to find the first
// repeated character in a string
#include <bits/stdc++.h>
using namespace std;
 
// Returns first repeating character in str.
char firstRepeating(string &str)
{
    int n=str.size();
     
    char ans;
    int index=INT_MAX;
     
    for(int i=0;i<n;i++){
        char temp=str[i];
      //Checking that character in temp repeats or not by running a for loop
        for(int j=i+1;j<n;j++){
           if(str[j]==temp){
       //if the index where it repeated is less than the index of the previously
       //repeated character then store this character in ans variable
       //and its index where it repeated in index variable
             if(j<index){
                 index=j;
                 ans=str[j];
             
            
           }
        }
    }
     
    return ans;
     
}
 
// Driver method to test above method
int main ()
{
    string str = "geeksforgeeks";
    cout << firstRepeating(str);
    return 0;
}

                    

Java

import java.util.*;
 
public class Main
{
 
  // Returns first repeating character in str.
  static char firstRepeating(String str) {
    int n = str.length();
    char ans = ' ';
    int index = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
      char temp = str.charAt(i);
 
      // Checking that character in temp repeats or not by running a for loop
      for (int j = i + 1; j < n; j++)
      {
        if (str.charAt(j) == temp)
        {
 
          // if the index where it repeated is less than the index of the previously
          // repeated character then store this character in ans variable
          // and its index where it repeated in index variable
          if (j < index) {
            index = j;
            ans = str.charAt(j);
          }
        }
      }
    }
    return ans;
  }
   
  // Driver method to test above method
  public static void main(String[] args) {
    String str = "geeksforgeeks";
    System.out.println(firstRepeating(str));
  }
 
}

                    

Python3

def firstRepeating(str):
    n = len(str)
     
    ans = ''
    index = float('inf')
     
    for i in range(n):
        temp = str[i]
        # Checking that character in temp repeats or not by running a for loop
        for j in range(i+1, n):
            if str[j] == temp:
                # if the index where it repeated is less than the index of the previously
                # repeated character then store this character in ans variable
                # and its index where it repeated in index variable
                if j < index:
                    index = j
                    ans = str[j]
     
    return ans
     
# Driver method to test above method
if __name__ == '__main__':
    str = "geeksforgeeks"
    print(firstRepeating(str))

                    

C#

using System;
 
public class Program {
    // Returns first repeating character in str.
    static char FirstRepeating(string str)
    {
        int n = str.Length;
        char ans = '\0';
        int index = int.MaxValue;
        for (int i = 0; i < n; i++) {
            char temp = str[i];
            // Checking that character in temp repeats or
            // not by running a for loop
            for (int j = i + 1; j < n; j++) {
                if (str[j] == temp) {
                    // if the index where it repeated is
                    // less than the index of the previously
                    // repeated character then store this
                    // character in ans variable and its
                    // index where it repeated in index
                    // variable
                    if (j < index) {
                        index = j;
                        ans = str[j];
                    }
                }
            }
        }
 
        return ans;
    }
 
    // Driver method to test above method
    static void Main(string[] args)
    {
        string str = "geeksforgeeks";
        Console.WriteLine(FirstRepeating(str));
    }
}
// This code is contributed by user_dtewbxkn77n

                    

Javascript

function firstRepeating(str) {
    const n = str.length;
    let ans = '\0';
    let index = Infinity;
     
    for (let i = 0; i < n; i++) {
        const temp = str[i];
        // Checking if the character in temp repeats or not
        for (let j = i + 1; j < n; j++) {
            if (str[j] === temp) {
                // If the index where it repeated is less than
                // the index of the previously repeated character,
                // then update ans and index variables
                if (j < index) {
                    index = j;
                    ans = str[j];
                }
            }
        }
    }
 
    return ans;
}
 
// Driver code
const str = "geeksforgeeks";
console.log(firstRepeating(str));

                    

Output
e









Time complexity : O(n2
Auxiliary Space : O(1)

We can Use Sorting to solve the problem in O(n Log n) time. Following are detailed steps.  

  • Copy the given array to an auxiliary array temp[].
  • Sort the temp array using a O(N log N) time sorting algorithm.
  • Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search. As soon as we find a character that occurs more than once, we return the character.

This step can be done in O(N Log N) time.

An efficient solution is to use Hashing to solve this in O(N) time on average. 

  • Create an empty hash.
  • Scan each character of input string and insert values to each keys in the hash.
  • When any character appears more than once, hash key value is increment by 1, and return the character.

Below image is a dry run of the above approach:


Below is the implementation of the above approach:

C++

// CPP program to find the first
// repeated character in a string
#include <bits/stdc++.h>
using namespace std;
 
// Returns first repeating character in str.
char firstRepeating(string &str)
{
    // Creates an empty hashset
    unordered_set<char> h;
 
    // Traverse the input array from left to right
    for (int i=0; i<str.length(); i++)
    {
        char c = str[i];
 
        // If element is already in hash set, update x
        // and then break
        if (h.find(c) != h.end())
            return c;
 
        else // Else add element to hash set
            h.insert(c);
    }
 
    // If there was no repeated character
    return '\0';
}
 
// Driver method to test above method
int main ()
{
    string str = "geeksforgeeks";
    cout << firstRepeating(str);
    return 0;
}

                    

Java

// Java program to find the first
// repeated character in a string
import java.util.*;
 
class Main
{
    // This function prints the first repeated
    // character in str[]
    static char firstRepeating(char str[])
    {
        // Creates an empty hashset
        HashSet<Character> h = new HashSet<>();
 
        // Traverse the input array from left to right
        for (int i=0; i<=str.length-1; i++)
        {
            char c = str[i];
 
            // If element is already in hash set, update x
            // and then break
            if (h.contains(c))
                return c;
 
            else // Else add element to hash set
                h.add(c);
        }
 
        return '\0';
    }
 
    // Driver method to test above method
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        char[] arr = str.toCharArray();
        System.out.println(firstRepeating(arr));
    }
}

                    

Python3

# Python program to find the first
# repeated character in a string
def firstRepeatedChar(str):
 
    h = {} # Create empty hash
 
    # Traverse each characters in string
    # in lower case order
    for ch in str:
 
        # If character is already present
        # in hash, return char
        if ch in h:
            return ch;
 
        # Add ch to hash
        else:
            h[ch] = 0
 
    return ''
 
 
# Driver code
print(firstRepeatedChar("geeksforgeeks"))

                    

C#

// C# program to find the first
// repeated character in a string
using System;
using System.Collections.Generic;
 
class GFG
{
// This function prints the first
// repeated character in str[]
public static char firstRepeating(char[] str)
{
    // Creates an empty hashset
    HashSet<char> h = new HashSet<char>();
 
    // Traverse the input array
    // from left to right
    for (int i = 0; i <= str.Length - 1; i++)
    {
        char c = str[i];
 
        // If element is already in hash set,
        // update x and then break
        if (h.Contains(c))
        {
            return c;
        }
 
        else // Else add element to hash set
        {
            h.Add(c);
        }
    }
 
    return '\0';
}
 
// Driver Code
public static void Main(string[] args)
{
    string str = "geeksforgeeks";
    char[] arr = str.ToCharArray();
    Console.WriteLine(firstRepeating(arr));
}
}
 
// This code is contributed by Shrikant13

                    

Javascript

<script>
 
// Javascript program to find the first
// repeated character in a string
     
// This function prints the first repeated
// character in str[]
function firstRepeating(str)
{
     
    // Creates an empty hashset
    let h = new Set();
     
    // Traverse the input array from left to right
    for(let i = 0; i <= str.length - 1; i++)
    {
        let c = str[i];
 
        // If element is already in hash
        // set, update x and then break
        if (h.has(c))
            return c;
             
        // Else add element to hash set
        else
            h.add(c);
    }
    return '\0';
}
 
// Driver code
let str = "geeksforgeeks";
document.write(firstRepeating(str));
 
// This code is contributed by avanitrachhadiya2155
 
</script>

                    

PHP

<?php
// PHP program to find the first repeated
// character in a string
 
// Returns first repeating character in str.
function firstRepeating($str)
{
    // Creates an empty hashset
    $h = array();
 
    // Traverse the input array
    // from left to right
    for ($i = 0; $i < strlen($str); $i++)
    {
        $c = $str[$i];
 
        // If element is already in hash
        // set, update x and then break
        if (array_search($c, $h))
            return $c;
 
        else // Else add element to hash set
            array_push($h, $c);
    }
 
    // If there was no repeated character
    return '\0';
}
 
// Driver Code
$str = "geeksforgeeks";
echo firstRepeating($str);
 
// This code is contributed by ita_c
?>

                    

Output
e









Time complexity : O(n) 
Auxiliary Space : O(n)

OPTIMIZED APPROACH:

Intuition:

  1. We create a array of size 26.
  2. then we increase the value of that character by 1 and if same character comes again, then we return that characeter.

Implementation:

C++

#include <iostream>
#include <string>
using namespace std;
 
// CPP program to find the first
// repeated character in a string
 
// Function to find the first repeated character in a string
string firstRepChar(string s)
{
    // Create an array to store the count of characters
    int a[26] = { 0 };
 
    // Iterate through each character in the string
    for (int i = 0; i < s.length(); i++) {
        char ch = s[i];
 
        // If the count of the character is not zero,
        // it means the character is repeated, so we return
        // it
        if (a[ch - 'a'] != 0)
            return string(1, ch);
        else
            // Increment the count of the character in the
            // array
            a[ch - 'a']++;
    }
 
    // If no character is repeated, return "-1"
    return "-1";
}
 
// Driver Code
int main()
{
 
    string str = "geeksforgeeks";
 
    // Call the function to find the first repeated
    // character
    cout << firstRepChar(str);
 
    return 0;
}
 
// This code is contributed by Veerendra_Singh_Rajpoot

                    

Java

// Java program to find the first
// repeated character in a string
 
import java.io.*;
import java.util.*;
 
class GFG {
    static String firstRepChar(String s)
    {
        // code here
        int a[] = new int[26];
 
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
 
            if (a[ch - 'a'] != 0)
                return Character.toString(ch);
            else
                a[ch - 'a']++;
        }
        return "-1";
    }
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        System.out.println(firstRepChar(str));
    }
}
// This code is contributed by Raunak Singh

                    

Python3

def first_rep_char(s):
    """
    Function to find the first repeated character in a string
    """
    # Create a dictionary to store the count of characters
    char_count = {}
 
    # Iterate through each character in the string
    for ch in s:
        # If the character is already in the dictionary, it means it is repeated
        if ch in char_count:
            return ch
        else:
            # Increment the count of the character in the dictionary
            char_count[ch] = 1
 
    # If no character is repeated, return "-1"
    return "-1"
 
 
if __name__ == "__main__":
    str = "geeksforgeeks"
 
    # Call the function to find the first repeated character
    print(first_rep_char(str))

                    

C#

using System;
using System.Collections.Generic;
 
public class GFG
{
    // Function to find the first repeated character in a string
    public static char FindFirstRepeatedChar(string str)
    {
        // Create a dictionary to store the count of characters
        Dictionary<char, int> charCount = new Dictionary<char, int>();
 
        // Iterate through each character in the string
        foreach (char ch in str)
        {
            // If the character is already in the dictionary,
           // it means it is repeated
          // So, we return it
            if (charCount.ContainsKey(ch))
            {
                return ch;
            }
            else
            {
                // Add the character to the dictionary with a count of 1
                charCount[ch] = 1;
            }
        }
 
        // If no character is repeated, return '\0' (null character)
        return '\0';
    }
 
    // Main method
    public static void Main(string[] args)
    {
        string str = "geeksforgeeks";
 
        // Call the function to find the first repeated character
        char firstRepeatedChar = FindFirstRepeatedChar(str);
 
        if (firstRepeatedChar != '\0')
        {
            Console.WriteLine("First repeated character: " + firstRepeatedChar);
        }
        else
        {
            Console.WriteLine("No repeated character found.");
        }
    }
}

                    

Javascript

// Function to find the first repeated character in a string
function findFirstRepeatedChar(str) {
    // Create a Map to store the count of characters
    let charCount = new Map();
 
    // Iterate through each character in the string
    for (let ch of str) {
        // If the character is already in the Map,
        // it means it is repeated
        // So, we return it
        if (charCount.has(ch)) {
            return ch;
        } else {
            // Add the character to the Map with a count of 1
            charCount.set(ch, 1);
        }
    }
 
    // If no character is repeated, return '\0' (null character)
    return '\0';
}
 
 
let str = "geeksforgeeks";
 
// Call the function to find the first repeated character
let firstRepeatedChar = findFirstRepeatedChar(str);
if (firstRepeatedChar !== '\0') {
        console.log("First repeated character:", firstRepeatedChar);
  } else {
        console.log("No repeated character found.");
  }
   

                    

Output
e








Time Complexity:  O(N), because N is the length of the string
Space Complexity: O(1)


Similar Problem: finding first non-repeated character in a string.



 



Last Updated : 20 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads