Find the Earliest Repeating Character
Last Updated :
07 Nov, 2024
Given a string S of length n, the task is to find the earliest repeated character in it. The earliest repeated character means, the character that occurs more than once and whose second occurrence has the smallest index.
Example:
Input: s = "geeksforgeeks"
Output: e
Explanation: e is the first element that repeats
Input: s = "hello geeks"
Output: l
Explanation: l is the first element that repeats
[Naive Approach] Using Two Nested Loops - O(n2) time and O(1) auxiliary space
The simplest way to solve this problem is to use a simple nested loop. The key idea here is to iterate through each character in the string and for each character, check if it has already appeared earlier in the string. If a character is found to be repeating, returned the currently picked character immediately as the result. If no character repeats, the returns "-1".
C++
#include <bits/stdc++.h>
using namespace std;
string firstRepChar(string& s)
{
// Get the size of the input string
int n = s.size();
// Iterate through each character in the string
for (int i = 0; i < n; i++) {
// Check if the current character is a repeating
// character
for (int j = 0; j < i; j++) {
if (s[i] == s[j]) {
// Create a string to hold the repeating
// character
string result = "";
result += s[i];
return result;
}
}
}
// If no repeating character is found, return "-1"
return "-1";
}
// Driver code
int main()
{
string s = "geeksforgeeks";
cout << firstRepChar(s);
return 0;
}
Java
import java.util.Scanner;
public class FirstRepeatingCharacter {
// Function to find the first repeating character in the
// string
public static String firstRepChar(String s)
{
// Get the size of the input string
int n = s.length();
// Iterate through each character in the string
for (int i = 0; i < n; i++) {
// Check if the current character is a repeating
// character
for (int j = 0; j < i; j++) {
if (s.charAt(i) == s.charAt(j)) {
// Create a string to hold the repeating
// character
return Character.toString(s.charAt(i));
}
}
}
// If no repeating character is found, return "-1"
return "-1";
}
public static void main(String[] args)
{
// Example usage:
String s = "geeksforgeeks";
// Print the result of the function
System.out.println(firstRepChar(s));
}
}
Python
def firstRepChar(s):
# Get the size of the input string
n = len(s)
# Iterate through each character in the string
for i in range(n):
# Check if the current character is a repeating character
for j in range(i):
if s[i] == s[j]:
# Return the repeating character
return s[i]
# If no repeating character is found, return "-1"
return "-1"
# Example usage:
s = "geeksforgeeks"
print(firstRepChar(s))
C#
using System;
public class Program {
// Function to find the first repeating character in the
// string
public static string FirstRepChar(string s)
{
// Get the size of the input string
int n = s.Length;
// Iterate through each character in the string
for (int i = 0; i < n; i++) {
// Check if the current character is a repeating
// character
for (int j = 0; j < i; j++) {
if (s[i] == s[j]) {
// Return the repeating character
return s[i].ToString();
}
}
}
// If no repeating character is found, return "-1"
return "-1";
}
public static void Main()
{
// Example usage:
string s = "geeksforgeeks";
// Print the result of the function
Console.WriteLine(FirstRepChar(s));
}
}
JavaScript
function firstRepChar(s) {
// Get the size of the input string
let n = s.length;
// Iterate through each character in the string
for (let i = 0; i < n; i++) {
// Check if the current character
// is a repeating character
for (let j = 0; j < i; j++) {
if (s[i] === s[j]) {
// Return the repeating character
return s[i];
}
}
}
// If no repeating character is found, return "-1"
return "-1";
}
// Example usage:
let s = "geeksforgeeks";
console.log(firstRepChar(s));
Time Complexity: O(n2)
Auxiliary Space: O(1)
[Expected Approach] Using Frequency Counting - O(n) time and O(1) auxiliary space
The main idea behind this approach is to efficiently track the frequency/occurrences of each character in the string using an array or hash table. Here we have used array for the same.
Here is a more detailed step-by-step explanation of the approach:
- We create an array of size 26 to store the count of each character. The size 26 is chosen because there are 26 letters in the English alphabet. Each index of this array will correspond to a character from 'a' to 'z'. For example, the index 0 corresponds to 'a', index 1 corresponds to 'b', and so on.
- We iterate through each character in the input string. For each character, we calculate its corresponding index in the array by subtracting the ASCII value of 'a' from the ASCII value of the character. This way, 'a' maps to index 0, 'b' maps to index 1, and so forth.
- For each character in the string, we increment the value at its corresponding index in the array. If the value at this index is greater than 0, it means the character has appeared before, and we return it as the first repeated character.
- If we traverse the entire string and do not find any repeated characters, we return "-1" to indicate that there are no repeated characters in the string.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the first repeated character in a string
string firstRepChar(string& s)
{
// Create an array to store the count of characters
int charCount[26] = { 0 };
// Iterate through each character in the string
for (int i = 0; i < s.length(); i++) {
char ch = s[i];
// Calculate the index in the array for this
// character
int index = ch - 'a';
// If the count of the character is not zero,
// it means the character is repeated, so we return
// it
if (charCount[index] != 0)
return string(1, ch);
// Increment the count of the character in the array
charCount[index]++;
}
// If no character is repeated, return "-1"
return "-1";
}
// Driver Code
int main()
{
string s = "geeksforgeeks";
// Call the function to find the first repeated
// character
cout << firstRepChar(s);
return 0;
}
Java
import java.util.Arrays;
public class FirstRepeatingCharacter {
// Function to find the first repeated character in a
// string
public static String firstRepChar(String s)
{
// Create an array to store the count of characters
int[] charCount = new int[26];
// Iterate through each character in the string
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// Calculate the index in the array for this
// character
int index = ch - 'a';
// If the count of the character is not zero,
// it means the character is repeated, so we
// return it
if (charCount[index] != 0) {
return Character.toString(ch);
}
// Increment the count of the character in the
// array
charCount[index]++;
}
// If no character is repeated, return "-1"
return "-1";
}
public static void main(String[] args)
{
// Example usage:
String s = "geeksforgeeks";
// Print the result of the function
System.out.println(firstRepChar(s));
}
}
Python
def firstRepChar(s):
# Create an array to store the count of characters
charCount = [0] * 26
# Iterate through each character in the string
for ch in s:
# Calculate the index in the array for this character
index = ord(ch) - ord('a')
# If the count of the character is not zero,
# it means the character is repeated, so we return it
if charCount[index] != 0:
return ch
# Increment the count of the character in the array
charCount[index] += 1
# If no character is repeated, return "-1"
return "-1"
# Example usage:
s = "geeksforgeeks"
print(firstRepChar(s))
C#
using System;
public class Program {
// Function to find the first repeated character in a
// string
public static string FirstRepChar(string s)
{
// Create an array to store the count of characters
int[] charCount = new int[26];
// Iterate through each character in the string
foreach(char ch in s)
{
// Calculate the index in the array for this
// character
int index = ch - 'a';
// If the count of the character is not zero,
// it means the character is repeated, so we
// return it
if (charCount[index] != 0) {
return ch.ToString();
}
// Increment the count of the character in the
// array
charCount[index]++;
}
// If no character is repeated, return "-1"
return "-1";
}
public static void Main()
{
// Example usage:
string s = "geeksforgeeks";
// Print the result of the function
Console.WriteLine(FirstRepChar(s));
}
}
JavaScript
function firstRepChar(s) {
// Create an array to store the count of characters
let charCount = new Array(26).fill(0);
// Iterate through each character in the string
for (let i = 0; i < s.length; i++) {
let ch = s[i];
// Calculate the index in the array for this character
let index = ch.charCodeAt(0) - 'a'.charCodeAt(0);
// If the count of the character is not zero,
// it means the character is repeated, so we return it
if (charCount[index] !== 0) {
return ch;
}
// Increment the count of the character in the array
charCount[index]++;
}
// If no character is repeated, return "-1"
return "-1";
}
// Example usage:
let s = "geeksforgeeks";
console.log(firstRepChar(s));
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Problem:
Similar Reads
K'th Non-repeating Character Given a string str of length n (1 <= n <= 106) and a number k, the task is to find the kth non-repeating character in the string.Examples: Input : str = geeksforgeeks, k = 3Output : rExplanation: First non-repeating character is f, second is o and third is r.Input : str = geeksforgeeks, k = 2O
14 min read
First non-repeating character in a stream Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
15+ min read
Kâth Non-repeating Character in Python We need to find the first K characters in a string that do not repeat within the string. This involves identifying unique characters and their order of appearance. We are given a string s = "geeksforgeeks" we need to return the non repeating character from the string which is 'r' in this case. This
4 min read
Find the last non repeating character in string Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Inpu
5 min read
First non-repeating character of given string Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'.Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat.Input: s = "racecar"Output: 'e'Ex
9 min read