Find the Earliest Repeating Character
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 repeatsInput: s = "hello geeks"
Output: l
Explanation: l is the first element that repeats
Table of Content
[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".
#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;
}
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));
}
}
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))
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));
}
}
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));
Output
e
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.
#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;
}
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));
}
}
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))
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));
}
}
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));
Output
e
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Problem: