Find the Earliest Repeating Character (original) (raw)

Last Updated : 23 Jul, 2025

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

Try It Yourselfredirect icon

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".

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:

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: