Find repeated character present first in a string
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.
Implementation:
C++
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
int findRepeatFirstN2( char * s)
{
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;
}
int main()
{
char str[] = "geeksforgeeks" ;
int pos = findRepeatFirstN2(str);
if (pos == -1)
cout << "Not found" ;
else
cout << str[pos];
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int findRepeatFirstN2( char * s)
{
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;
}
int main()
{
char str[] = "geeksforgeeks" ;
int pos = findRepeatFirstN2(str);
if (pos == -1)
printf ( "Not found" );
else
printf ( "%c" , str[pos]);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int findRepeatFirstN2(String s)
{
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;
}
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));
}
}
|
Python3
def findRepeatFirstN2(s):
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
if __name__ = = "__main__" :
str = "geeksforgeeks"
pos = findRepeatFirstN2( str )
if (pos = = - 1 ):
print ( "Not found" )
else :
print ( str [pos])
|
C#
using System;
class GFG {
static int findRepeatFirstN2( string s)
{
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;
}
static public void Main ()
{
string str = "geeksforgeeks" ;
int pos = findRepeatFirstN2(str);
if (pos == -1)
Console.WriteLine( "Not found" );
else
Console.WriteLine( str[pos]);
}
}
|
PHP
<?php
function findRepeatFirstN2( $s )
{
$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 ;
}
$str = "geeksforgeeks" ;
$pos = findRepeatFirstN2( $str );
if ( $pos == -1)
echo ( "Not found" );
else
echo ( $str [ $pos ]);
?>
|
Javascript
<script>
function findRepeatFirstN2(s)
{
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;
}
let str = "geeksforgeeks" ;
let pos = findRepeatFirstN2(str);
if (pos == -1)
document.write( "Not found" );
else
document.write(str[pos]);
</script>
|
Space complexity :- O(1)
Optimization by counting occurrences
This solution is optimized by using the following techniques:
- 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.
- We run a loop on the hash array and now we find the minimum position of any character repeated.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
#define MAX_CHAR 256
int findRepeatFirst( char * s)
{
int p = -1, i, k;
int hash[MAX_CHAR] = { 0 };
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)
p = pos[i];
else if (p > pos[i])
p = pos[i];
}
}
return p;
}
int main()
{
char str[] = "geeksforgeeks" ;
int pos = findRepeatFirst(str);
if (pos == -1)
cout << "Not found" ;
else
cout << str[pos];
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 256
int findRepeatFirst( char * s)
{
int p = -1, i, k;
int hash[MAX_CHAR] = { 0 };
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)
p = pos[i];
else if (p > pos[i])
p = pos[i];
}
}
return p;
}
int main()
{
char str[] = "geeksforgeeks" ;
int pos = findRepeatFirst(str);
if (pos == -1)
printf ( "Not found" );
else
printf ( "%c" , str[pos]);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GFG
{
public static int findRepeatFirst(String s)
{
int p = - 1 , i, k;
int MAX_CHAR = 256 ;
int hash[] = new int [MAX_CHAR];
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 )
p = pos[i];
else if (p > pos[i])
p = pos[i];
}
}
return p;
}
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));
}
}
|
Python3
MAX_CHAR = 256
def findRepeatFirst(s):
p = - 1
hash = [ 0 for i in range (MAX_CHAR)]
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 ):
p = pos[i]
elif (p > pos[i]):
p = pos[i]
return p
if __name__ = = '__main__' :
str = "geeksforgeeks"
pos = findRepeatFirst( str );
if (pos = = - 1 ):
print ( "Not found" )
else :
print ( str [pos])
|
C#
using System;
public class GFG
{
public static int findRepeatFirst( string s)
{
int p = -1, i, k;
int MAX_CHAR = 256;
int []hash = new int [MAX_CHAR];
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)
p = pos[i];
else if (p > pos[i])
p = pos[i];
}
}
return p;
}
public static void Main()
{
string str = "geeksforgeeks" ;
int pos = findRepeatFirst(str);
if (pos == -1)
Console.Write( "Not found" );
else
Console.Write(str[pos]);
}
}
|
Javascript
<script>
function findRepeatFirst(s)
{
let p = -1, i, k;
let MAX_CHAR = 256;
let hash = new Array(MAX_CHAR);
hash.fill(0);
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)
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]);
</script>
|
Time Complexity: O(N)
Auxiliary space: O(1)
Method #3:Using Built-in Python Functions:
Approach:
- 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:
C++
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
void printrepeated(string str)
{
unordered_map< char , int > freq;
for ( char c : str) {
freq++;
}
for ( char c : str) {
if (freq > 1) {
cout << c << endl;
break ;
}
}
}
int main()
{
string str = "geeksforgeeks" ;
printrepeated(str);
return 0;
}
|
Java
import java.util.HashMap;
public class Main {
static void printrepeated(String str)
{
HashMap<Character, Integer> freq
= new HashMap<Character, Integer>();
for ( int i = 0 ; i < str.length(); i++) {
char c = str.charAt(i);
freq.put(c, freq.getOrDefault(c, 0 ) + 1 );
}
for ( int i = 0 ; i < str.length(); i++) {
char c = str.charAt(i);
if (freq.get(c) > 1 ) {
System.out.println(c);
break ;
}
}
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
printrepeated(str);
}
}
|
Python3
from collections import Counter
def printrepeated(string):
freq = Counter(string)
for i in string:
if (freq[i] > 1 ):
print (i)
break
string = "geeksforgeeks"
printrepeated(string)
|
C#
Javascript
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Solving just by single traversal of the given string.
Algorithm :
- Traverse the string from left to right.
- If current character is not present in hash map, Then push this character along with its Index.
- 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.
- If the current index is smaller, then update the index.
C++
Java
import java.util.*;
public class GFG {
public static int INT_MAX = 2147483647 ;
public static char firstRep(String s)
{
HashMap<Character, Integer> map
= new HashMap<Character, Integer>();
char c = '#' ;
int index = INT_MAX;
for ( int i = 0 ; i < s.length(); i++) {
char p = s.charAt(i);
if (!map.containsKey(p)) {
map.put(p, i);
}
else {
if (map.get(p) < index) {
index = map.get(p);
c = p;
}
}
}
return c;
}
public static void main(String[] args)
{
String s = "abccdbd" ;
System.out.print(firstRep(s));
System.out.print( "\n" );
}
}
|
Python3
INT_MAX = 2147483647
def firstRep(s):
map = dict ()
c = '#'
index = INT_MAX
i = 0
while (i < len (s)):
p = s[i]
if ( not (p in map .keys())):
map [p] = i
else :
if ( map .get(p) < index):
index = map .get(p)
c = p
i + = 1
return c
if __name__ = = "__main__" :
s = "abccdbd"
print (firstRep(s), end = "")
print ( "\n" , end = "")
|
C#
using System;
using System.Collections.Generic;
public static class GFG {
static int INT_MAX = 2147483647;
public static char firstRep( string s)
{
Dictionary< char , int > map
= new Dictionary< char , int >();
char c = '#' ;
int index = INT_MAX;
for ( int i = 0; i < s.Length; i++) {
char p = s[i];
if (!map.ContainsKey(p)) {
map[p] = i;
}
else {
if (map[p] < index) {
index = map[p];
c = p;
}
}
}
return c;
}
public static void Main()
{
string s = "abccdbd" ;
Console.Write(firstRep(s));
Console.Write( "\n" );
}
}
|
Javascript
<script>
const INT_MAX = 2147483647
function firstRep(s)
{
map = new Map();
let c = '#' ;
let index=INT_MAX;
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;
}
const s= "abccdbd" ;
document.write(firstRep(s));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(1), as there will be a constant number of characters present in the string.
More optimized Solution Repeated Character Whose First Appearance is Leftmost
Last Updated :
13 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...