Given a string, find the repeated character present first in the string. (Not the first repeated character, found here.)
Examples:
Input : neveropen
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++
// C++ program to find the first
// character that is repeated
#include <bits/stdc++.h>
#include <string.h>
usingnamespacestd;
intfindRepeatFirstN2(char* s)
{
// this is O(N^2) method
intp = -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;
}
returnp;
}
// Driver code
intmain()
{
charstr[] = "neveropen";
intpos = findRepeatFirstN2(str);
if(pos == -1)
cout << "Not found";
else
cout << str[pos];
return0;
}
// This code is contributed
// by Akanksha Rai
C
// C program to find the first character that
// is repeated
#include <stdio.h>
#include <string.h>
intfindRepeatFirstN2(char* s)
{
// this is O(N^2) method
intp = -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;
}
returnp;
}
// Driver code
intmain()
{
charstr[] = "neveropen";
intpos = findRepeatFirstN2(str);
if(pos == -1)
printf("Not found");
else
printf("%c", str[pos]);
return0;
}
Java
// Java program to find the first character
// that is repeated
importjava.io.*;
importjava.util.*;
classGFG {
staticintfindRepeatFirstN2(String s)
{
// this is O(N^2) method
intp = -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;
}
returnp;
}
// Driver code
staticpublicvoidmain (String[] args)
{
String str = "neveropen";
intpos = 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
# Python3 program to find the first
# character that is repeated
deffindRepeatFirstN2(s):
# this is O(N^2) method
p =-1
fori inrange(len(s)):
forj inrange(i +1, len(s)):
if(s[i] ==s[j]):
p =i
break
if(p !=-1):
break
returnp
# Driver code
if__name__ =="__main__":
str="neveropen"
pos =findRepeatFirstN2(str)
if(pos ==-1):
print("Not found")
else:
print(str[pos])
# This code is contributed
# by ChitraNayal
C#
// C# program to find the first character
// that is repeated
usingSystem;
classGFG {
staticintfindRepeatFirstN2(strings)
{
// this is O(N^2) method
intp = -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;
}
returnp;
}
// Driver code
staticpublicvoidMain ()
{
stringstr = "neveropen";
intpos = findRepeatFirstN2(str);
if(pos == -1)
Console.WriteLine("Not found");
else
Console.WriteLine( str[pos]);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the first
// character that is repeated
functionfindRepeatFirstN2($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= "neveropen";
$pos= findRepeatFirstN2($str);
if($pos== -1)
echo("Not found");
else
echo($str[$pos]);
// This code is contributed by jit_t
?>
Javascript
<script>
// Javascript program to find the first
// character that is repeated
functionfindRepeatFirstN2(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;
}
returnp;
}
// Driver code
let str = "neveropen";
let pos = findRepeatFirstN2(str);
if(pos == -1)
document.write("Not found");
else
document.write(str[pos]);
// This code is contributed by suresh07
</script>
Output
g
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++
// C++ program to find the first character that
// is repeated
#include<bits/stdc++.h>
usingnamespacestd;
// 256 is taken just to ensure nothing is left,
// actual max ASCII limit is 128
#define MAX_CHAR 256
intfindRepeatFirst(char* s)
{
// this is optimized method
intp = -1, i, k;
// initialized counts of occurrences of
// elements as zero
inthash[MAX_CHAR] = { 0 };
// initialized positions
intpos[MAX_CHAR];
for(i = 0; i < strlen(s); i++) {
k = (int)s[i];
if(hash[k] == 0) {
hash[k]++;
pos[k] = i;
} elseif(hash[k] == 1)
hash[k]++;
}
for(i = 0; i < MAX_CHAR; i++) {
if(hash[i] == 2) {
if(p == -1) // base case
p = pos[i];
elseif(p > pos[i])
p = pos[i];
}
}
returnp;
}
// Driver code
intmain()
{
charstr[] = "neveropen";
intpos = findRepeatFirst(str);
if(pos == -1)
cout << "Not found";
else
cout << str[pos];
return0;
}
// This code is contributed
// by Akanksha Rai
C
// 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
intfindRepeatFirst(char* s)
{
// this is optimized method
intp = -1, i, k;
// initialized counts of occurrences of
// elements as zero
inthash[MAX_CHAR] = { 0 };
// initialized positions
intpos[MAX_CHAR];
for(i = 0; i < strlen(s); i++) {
k = (int)s[i];
if(hash[k] == 0) {
hash[k]++;
pos[k] = i;
} elseif(hash[k] == 1)
hash[k]++;
}
for(i = 0; i < MAX_CHAR; i++) {
if(hash[i] == 2) {
if(p == -1) // base case
p = pos[i];
elseif(p > pos[i])
p = pos[i];
}
}
returnp;
}
// Driver code
intmain()
{
charstr[] = "neveropen";
intpos = findRepeatFirst(str);
if(pos == -1)
printf("Not found");
else
printf("%c", str[pos]);
return0;
}
Java
// Java Program to find the first character
// that is repeated
importjava.util.*;
importjava.lang.*;
publicclassGFG
{
publicstaticintfindRepeatFirst(String s)
{
// this is optimized method
intp = -1, i, k;
// initialized counts of occurrences of
// elements as zero
intMAX_CHAR = 256;
inthash[] = newint[MAX_CHAR];
// initialized positions
intpos[] = newint[MAX_CHAR];
for(i = 0; i < s.length(); i++)
{
k = (int)s.charAt(i);
if(hash[k] == 0)
{
hash[k]++;
pos[k] = i;
}
elseif(hash[k] == 1)
hash[k]++;
}
for(i = 0; i < MAX_CHAR; i++)
{
if(hash[i] == 2)
{
if(p == -1) // base case
p = pos[i];
elseif(p > pos[i])
p = pos[i];
}
}
returnp;
}
// Driver code
publicstaticvoidmain(String[] args)
{
String str = "neveropen";
intpos = findRepeatFirst(str);
if(pos == -1)
System.out.println("Not found");
else
System.out.println(str.charAt(pos));
}
}
// Code Contributed by Mohit Gupta_OMG
Python3
# 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
deffindRepeatFirst(s):
# this is optimized method
p =-1
# initialized counts of occurrences
# of elements as zero
hash=[0fori inrange(MAX_CHAR)]
# initialized positions
pos =[0fori inrange(MAX_CHAR)]
fori inrange(len(s)):
k =ord(s[i])
if(hash[k] ==0):
hash[k] +=1
pos[k] =i
elif(hash[k] ==1):
hash[k] +=1
fori inrange(MAX_CHAR):
if(hash[i] ==2):
if(p ==-1): # base case
p =pos[i]
elif(p > pos[i]):
p =pos[i]
returnp
# Driver code
if__name__ =='__main__':
str="neveropen"
pos =findRepeatFirst(str);
if(pos ==-1):
print("Not found")
else:
print(str[pos])
# This code is contributed by
# Shashank_Sharma
C#
// C# Program to find the first character
// that is repeated
usingSystem;
publicclassGFG
{
publicstaticintfindRepeatFirst(strings)
{
// this is optimized method
intp = -1, i, k;
// initialized counts of occurrences of
// elements as zero
intMAX_CHAR = 256;
int[]hash = newint[MAX_CHAR];
// initialized positions
int[]pos = newint[MAX_CHAR];
for(i = 0; i < s.Length; i++)
{
k = (int)s[i];
if(hash[k] == 0)
{
hash[k]++;
pos[k] = i;
}
elseif(hash[k] == 1)
hash[k]++;
}
for(i = 0; i < MAX_CHAR; i++)
{
if(hash[i] == 2)
{
if(p == -1) // base case
p = pos[i];
elseif(p > pos[i])
p = pos[i];
}
}
returnp;
}
// Driver code
publicstaticvoidMain()
{
stringstr = "neveropen";
intpos = findRepeatFirst(str);
if(pos == -1)
Console.Write("Not found");
else
Console.Write(str[pos]);
}
}
// This code is contributed by nitin mittal.
Javascript
<script>
// Javascript Program to find the first character that is repeated
functionfindRepeatFirst(s)
{
// this is optimized method
let p = -1, i, k;
// initialized counts of occurrences of
// elements as zero
let MAX_CHAR = 256;
let hash = newArray(MAX_CHAR);
hash.fill(0);
// initialized positions
let pos = newArray(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;
}
elseif(hash[k] == 1)
hash[k]++;
}
for(i = 0; i < MAX_CHAR; i++)
{
if(hash[i] == 2)
{
if(p == -1) // base case
p = pos[i];
elseif(p > pos[i])
p = pos[i];
}
}
returnp;
}
let str = "neveropen";
let pos = findRepeatFirst(str);
if(pos == -1)
document.write("Not found");
else
document.write(str[pos]);
// This code is contributed by rameshtravel07.
</script>
Output
g
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>
usingnamespacestd;
// Function which repeats
// first repeating character
voidprintrepeated(string str)
{
// Calculating frequencies
// using unordered_map
unordered_map<char, int> freq;
for(charc : str) {
freq++;
}
// Traverse the string
for(charc : str) {
if(freq > 1) {
cout << c << endl;
break;
}
}
}
// Driver code
intmain()
{
string str = "neveropen";
// passing string to printrepeated function
printrepeated(str);
return0;
}
Java
importjava.util.HashMap;
publicclassMain {
// Function which repeats
// first repeating character
staticvoidprintrepeated(String str)
{
// Calculating frequencies
// using HashMap
HashMap<Character, Integer> freq
= newHashMap<Character, Integer>();
for(inti = 0; i < str.length(); i++) {
charc = str.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
// Traverse the string
for(inti = 0; i < str.length(); i++) {
charc = str.charAt(i);
if(freq.get(c) > 1) {
System.out.println(c);
break;
}
}
}
// Driver code
publicstaticvoidmain(String[] args)
{
String str = "neveropen";
printrepeated(str);
}
}
Python3
# Python implementation
fromcollections importCounter
# Function which repeats
# first repeating character
defprintrepeated(string):
# Calculating frequencies
# using Counter function
freq =Counter(string)
# Traverse the string
fori instring:
if(freq[i] > 1):
print(i)
break
# Driver code
string ="neveropen"
# passing string to printrepeated function
printrepeated(string)
# this code is contributed by vikkycirus
C#
usingSystem;
usingSystem.Collections.Generic;
classProgram
{
// Function which repeats
// first repeating character
staticvoidPrintRepeated(stringstr)
{
// Calculating frequencies
// using Dictionary
Dictionary<char, int> freq
= newDictionary<char, int>();
foreach(charc instr)
{
if(freq.ContainsKey(c)) {
freq++;
}
else{
freq = 1;
}
}
// Traverse the string
foreach(charc instr)
{
if(freq > 1) {
Console.WriteLine(c);
break;
}
}
}
// Driver code
staticvoidMain()
{
stringstr = "neveropen";
// passing string to PrintRepeated function
PrintRepeated(str);
Console.ReadLine();
}
}
// This code is contributed by user_dtewbxkn77n
Javascript
// JavaScript implementation
// Function which repeats
// first repeating character
functionprintrepeated(string) {
// Calculating frequencies
// using an object to store character counts
let freq = {};
for(let i = 0; i < string.length; i++) {
if(string[i] infreq) {
freq[string[i]] += 1;
} else{
freq[string[i]] = 1;
}
}
// Traverse the string
for(let i = 0; i < string.length; i++) {
if(freq[string[i]] > 1) {
console.log(string[i]);
break;
}
}
}
// Driver code
let string = "neveropen";
// passing string to printrepeated function
printrepeated(string);
// this code is contributed by princekumaras
Output
g
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++
#include <iostream>
#include<unordered_map>
#define INT_MAX 2147483647
usingnamespacestd;
// Function to find left most repeating character.
charfirstRep (string s)
{
unordered_map<char,int> map;
charc='#';
intindex=INT_MAX;
// single traversal of string.
for(inti=0;i<s.size();i++)
{
charp=s[i];
if(map.find(p)==map.end())map.insert({p,i});
else
{
if(map[p]<index)
{
index=map[p];
c=p;
}
}
}
returnc;
}
// Main function.
intmain() {
// Input string.
string s="abccdbd";
cout<<firstRep(s)<<endl;
return0;
}
// This code is contributed
// by rohan007
Java
// Java code to find the first repeating character in a
// string
importjava.util.*;
publicclassGFG {
publicstaticintINT_MAX = 2147483647;
// Function to find left most repeating character.
publicstaticcharfirstRep(String s)
{
HashMap<Character, Integer> map
= newHashMap<Character, Integer>();
charc = '#';
intindex = INT_MAX;
// single traversal of string.
for(inti = 0; i < s.length(); i++) {
charp = s.charAt(i);
if(!map.containsKey(p)) {
map.put(p, i);
}
else{
if(map.get(p) < index) {
index = map.get(p);
c = p;
}
}
}
returnc;
}
// Main function.
publicstaticvoidmain(String[] args)
{
// Input string.
String s = "abccdbd";
System.out.print(firstRep(s));
System.out.print("\n");
}
}
// This code is contributed by Aarti_Rathi
Python3
# Python3 code to find the first repeating character in a
# string
INT_MAX =2147483647
# Function to find left most repeating character.
deffirstRep(s):
map=dict()
c ='#'
index =INT_MAX
# single traversal of string.
i =0
while(i < len(s)):
p =s[i]
if(not(p inmap.keys())):
map[p] =i
else:
if(map.get(p) < index):
index =map.get(p)
c =p
i +=1
returnc
if__name__ =="__main__":
# Input string.
s ="abccdbd"
print(firstRep(s), end="")
print("\n", end="")
# This code is contributed by Aarti_Rathi
C#
// C# code to find the first repeating character in a string
usingSystem;
usingSystem.Collections.Generic;
publicstaticclassGFG {
staticintINT_MAX = 2147483647;
// Function to find left most repeating character.
publicstaticcharfirstRep(strings)
{
Dictionary<char, int> map
= newDictionary<char, int>();
charc = '#';
intindex = INT_MAX;
// single traversal of string.
for(inti = 0; i < s.Length; i++) {
charp = s[i];
if(!map.ContainsKey(p)) {
map[p] = i;
}
else{
if(map[p] < index) {
index = map[p];
c = p;
}
}
}
returnc;
}
// Main function.
publicstaticvoidMain()
{
// Input string.
strings = "abccdbd";
Console.Write(firstRep(s));
Console.Write("\n");
}
}
// This code is contributed by Aarti_Rathi
Javascript
<script>
// JavaScript code to find the first repeating character in a string
const INT_MAX = 2147483647
// Function to find left most repeating character.
functionfirstRep(s)
{
map = newMap();
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;
}
}
}
returnc;
}
// Driver code
// Input string.
const s="abccdbd";
document.write(firstRep(s));
// This code is contributed by shinjanpatra
</script>
Output
b
Time complexity: O(N) Auxiliary Space: O(1), as there will be a constant number of characters present in the string.
This article is contributed by Suprotik Dey. If you like neveropen 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 neveropen main page and help other Geeks.
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 neveropen!