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.

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++
#include <bits/stdc++.h>
using namespace std;
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];
for ( int j=i+1;j<n;j++){
if (str[j]==temp){
if (j<index){
index=j;
ans=str[j];
}
}
}
}
return ans;
}
int main ()
{
string str = "geeksforgeeks" ;
cout << firstRepeating(str);
return 0;
}
|
Java
import java.util.*;
public class Main
{
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);
for ( int j = i + 1 ; j < n; j++)
{
if (str.charAt(j) == temp)
{
if (j < index) {
index = j;
ans = str.charAt(j);
}
}
}
}
return ans;
}
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]
for j in range (i + 1 , n):
if str [j] = = temp:
if j < index:
index = j
ans = str [j]
return ans
if __name__ = = '__main__' :
str = "geeksforgeeks"
print (firstRepeating( str ))
|
C#
using System;
public class Program {
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];
for ( int j = i + 1; j < n; j++) {
if (str[j] == temp) {
if (j < index) {
index = j;
ans = str[j];
}
}
}
}
return ans;
}
static void Main( string [] args)
{
string str = "geeksforgeeks" ;
Console.WriteLine(FirstRepeating(str));
}
}
|
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];
for (let j = i + 1; j < n; j++) {
if (str[j] === temp) {
if (j < index) {
index = j;
ans = str[j];
}
}
}
}
return ans;
}
const str = "geeksforgeeks" ;
console.log(firstRepeating(str));
|
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++
#include <bits/stdc++.h>
using namespace std;
char firstRepeating(string &str)
{
unordered_set< char > h;
for ( int i=0; i<str.length(); i++)
{
char c = str[i];
if (h.find(c) != h.end())
return c;
else
h.insert(c);
}
return '\0' ;
}
int main ()
{
string str = "geeksforgeeks" ;
cout << firstRepeating(str);
return 0;
}
|
Java
import java.util.*;
class Main
{
static char firstRepeating( char str[])
{
HashSet<Character> h = new HashSet<>();
for ( int i= 0 ; i<=str.length- 1 ; i++)
{
char c = str[i];
if (h.contains(c))
return c;
else
h.add(c);
}
return '\0' ;
}
public static void main (String[] args)
{
String str = "geeksforgeeks" ;
char [] arr = str.toCharArray();
System.out.println(firstRepeating(arr));
}
}
|
Python3
def firstRepeatedChar( str ):
h = {}
for ch in str :
if ch in h:
return ch;
else :
h[ch] = 0
return ''
print (firstRepeatedChar( "geeksforgeeks" ))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static char firstRepeating( char [] str)
{
HashSet< char > h = new HashSet< char >();
for ( int i = 0; i <= str.Length - 1; i++)
{
char c = str[i];
if (h.Contains(c))
{
return c;
}
else
{
h.Add(c);
}
}
return '\0' ;
}
public static void Main( string [] args)
{
string str = "geeksforgeeks" ;
char [] arr = str.ToCharArray();
Console.WriteLine(firstRepeating(arr));
}
}
|
Javascript
<script>
function firstRepeating(str)
{
let h = new Set();
for (let i = 0; i <= str.length - 1; i++)
{
let c = str[i];
if (h.has(c))
return c;
else
h.add(c);
}
return '\0' ;
}
let str = "geeksforgeeks" ;
document.write(firstRepeating(str));
</script>
|
PHP
<?php
function firstRepeating( $str )
{
$h = array ();
for ( $i = 0; $i < strlen ( $str ); $i ++)
{
$c = $str [ $i ];
if ( array_search ( $c , $h ))
return $c ;
else
array_push ( $h , $c );
}
return '\0' ;
}
$str = "geeksforgeeks" ;
echo firstRepeating( $str );
?>
|
Time complexity : O(n)
Auxiliary Space : O(n)
OPTIMIZED APPROACH:
Intuition:
- We create a array of size 26.
- 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;
string firstRepChar(string s)
{
int a[26] = { 0 };
for ( int i = 0; i < s.length(); i++) {
char ch = s[i];
if (a[ch - 'a' ] != 0)
return string(1, ch);
else
a[ch - 'a' ]++;
}
return "-1" ;
}
int main()
{
string str = "geeksforgeeks" ;
cout << firstRepChar(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String firstRepChar(String s)
{
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));
}
}
|
Python3
def first_rep_char(s):
char_count = {}
for ch in s:
if ch in char_count:
return ch
else :
char_count[ch] = 1
return "-1"
if __name__ = = "__main__" :
str = "geeksforgeeks"
print (first_rep_char( str ))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static char FindFirstRepeatedChar( string str)
{
Dictionary< char , int > charCount = new Dictionary< char , int >();
foreach ( char ch in str)
{
if (charCount.ContainsKey(ch))
{
return ch;
}
else
{
charCount[ch] = 1;
}
}
return '\0' ;
}
public static void Main( string [] args)
{
string str = "geeksforgeeks" ;
char firstRepeatedChar = FindFirstRepeatedChar(str);
if (firstRepeatedChar != '\0' )
{
Console.WriteLine( "First repeated character: " + firstRepeatedChar);
}
else
{
Console.WriteLine( "No repeated character found." );
}
}
}
|
Javascript
function findFirstRepeatedChar(str) {
let charCount = new Map();
for (let ch of str) {
if (charCount.has(ch)) {
return ch;
} else {
charCount.set(ch, 1);
}
}
return '\0' ;
}
let str = "geeksforgeeks" ;
let firstRepeatedChar = findFirstRepeatedChar(str);
if (firstRepeatedChar !== '\0' ) {
console.log( "First repeated character:" , firstRepeatedChar);
} else {
console.log( "No repeated character found." );
}
|
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.
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!