Find repeated character present first in a string

Last Updated : 2 Oct, 2026

Given a string s consisting of lowercase English letters, find the first character that repeats in the string. If the string contains no repeating characters, return '#'.

Examples :

Input: s = "geeksforgeeks"
Output: 'g'
Explanation: 'g', 'e', 'k' and 's' are the repeating characters. Out of these, 'g' occurs first.

Explanation

Input: s = "abcde"
Output: '#'
Explanation: No repeating character present, so return '#'.

Try It Yourself
redirect icon

[Naive Approach] Check Each Character - O(n^2) Time and O(1) Space

The idea is to check each character of the string one by one from left to right.

For every character, scan the rest of the string to see if it appears again.

Return the first character for which a duplicate is found.

C++
#include <iostream>
#include <string>
using namespace std;

char firstRep(string s) {
    for (int i = 0; i < s.length(); i++) {
        for (int j = i + 1; j < s.length(); j++) {
            if (s[i] == s[j]) {
                return s[i];
            }
        }
    }
    return '#';
}

int main() {
    string s = "geeksforgeeks";
    cout << firstRep(s) << endl; // Output: g
    return 0;
}
Java
public class GFG {
    public static char firstRep(String s) {
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j < s.length(); j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    return s.charAt(i);
                }
            }
        }
        return '#';
    }
    
    public static void main(String[] args) {
        String s = "geeksforgeeks";
        System.out.println(firstRep(s)); // Output: g
    }
}
Python
def firstRep(s: str) -> str:
    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if s[i] == s[j]:
                return s[i]
    return '#'

if __name__ == "__main__":
    s = "geeksforgeeks"
    print(firstRep(s))  # Output: g
C#
using System;

public class GFG {
    public static char firstRep(string s) {
        for (int i = 0; i < s.Length; i++) {
            for (int j = i + 1; j < s.Length; j++) {
                if (s[i] == s[j]) {
                    return s[i];
                }
            }
        }
        return '#';
    }
    
    public static void Main(string[] args) {
        string s = "geeksforgeeks";
        Console.WriteLine(firstRep(s)); // Output: g
    }
}
JavaScript
function firstRep(s) {
    for (let i = 0; i < s.length; i++) {
        for (let j = i + 1; j < s.length; j++) {
            if (s[i] === s[j]) {
                return s[i];
            }
        }
    }
    return '#';
}

// Driver Code
const s = "geeksforgeeks";
console.log(firstRep(s)); // Output: g

Output
g

[Better Approach] Frequency Tracking - O(n) Time and O(1) Space

Since the string contains only lowercase English alphabets, we use a fixed-size frequency array (hash table) of size 26.

  • In the first pass, we traverse the string and increment the count of each character in our frequency array.
  • In the second pass, we traverse the string from left to right and check the frequency of each character. The first character we encounter whose frequency is greater than 1 is our answer. This ensures we find the character that repeats first based on its earliest appearance index.
  • If no character has a frequency greater than 1, we return '#'.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;

char firstRep(string s) {
    int hash[26] = {0};

    for (int i = 0; i < s.length(); ++i)
        hash[s[i] - 'a']++;

    for (int i = 0; i < s.length(); ++i) {
        if (hash[s[i] - 'a'] > 1)
            return s[i];
    }

    return '#';
}

int main() {
    string s = "geeksforgeeks";
    cout << firstRep(s) << endl; // Output: g
    return 0;
}
Java
public class GFG {
    public static char firstRep(String s) {
        int[] hash = new int[26];

        for (int i = 0; i < s.length(); i++) {
            hash[s.charAt(i) - 'a']++;
        }

        for (int i = 0; i < s.length(); i++) {
            if (hash[s.charAt(i) - 'a'] > 1) {
                return s.charAt(i);
            }
        }

        return '#';
    }
    
    public static void main(String[] args) {
        String s = "geeksforgeeks";
        System.out.println(firstRep(s)); // Output: g
    }
}
Python
def firstRep(s: str) -> str:
    hash_arr = [0] * 26

    for char in s:
        hash_arr[ord(char) - ord('a')] += 1

    for char in s:
        if hash_arr[ord(char) - ord('a')] > 1:
            return char

    return '#'

if __name__ == "__main__":
    s = "geeksforgeeks"
    print(firstRep(s))  # Output: g
C#
using System;

public class GFG {
    public static char firstRep(string s) {
        int[] hash = new int[26];

        for (int i = 0; i < s.Length; i++) {
            hash[s[i] - 'a']++;
        }

        for (int i = 0; i < s.Length; i++) {
            if (hash[s[i] - 'a'] > 1) {
                return s[i];
            }
        }

        return '#';
    }
    
    public static void Main(string[] args) {
        string s = "geeksforgeeks";
        Console.WriteLine(firstRep(s)); // Output: g
    }
}
JavaScript
function firstRep(s) {
    let hash = new Array(26).fill(0);

    for (let i = 0; i < s.length; i++) {
        hash[s.charCodeAt(i) - 97]++;
    }

    for (let i = 0; i < s.length; i++) {
        if (hash[s.charCodeAt(i) - 97] > 1) {
            return s[i];
        }
    }

    return '#';
}

// Driver Code
const s = "geeksforgeeks";
console.log(firstRep(s)); // Output: g

Output
g

[Expected Approach] Single Traversal - O(n) Time and O(1) Space

Instead of making two separate passes over the string, we process the string in a single traversal using a Hash Map to track indices.

  • We iterate through the string from left to right.
  • If a character is encountered for the first time, we store its index in the map.
  • If the character is already present in the map, it means it is a repeating character. We compare its first-seen index with our global minimum index tracking variable, updating it if the current index is smaller.
  • After checking the entire string, the character corresponding to the minimum index found is returned. If no character repeats, we return '#'
C++
#include <iostream>
#include <string>
#include <unordered_map>
#include <climits>
using namespace std;

char firstRep(string s) {
    unordered_map<char, int> mp;
    char res = '#';
    int minIndex = INT_MAX;

    for (int i = 0; i < s.length(); i++) {
        char ch = s[i];
        if (mp.find(ch) == mp.end()) {
            mp[ch] = i;
        } else {
            if (mp[ch] < minIndex) {
                minIndex = mp[ch];
                res = ch;
            }
        }
    }
    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << firstRep(s) << endl; // Output: g
    return 0;
}
Java
import java.util.HashMap;

public class GFG {
    public static char firstRep(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        char c = '#';
        int index = Integer.MAX_VALUE;

        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 = "geeksforgeeks";
        System.out.println(firstRep(s)); // Output: g
    }
}
Python
import sys

def firstRep(s: str) -> str:
    mp = {}
    c = '#'
    index = sys.maxsize

    for i in range(len(s)):
        p = s[i]
        if p not in mp:
            mp[p] = i
        else:
            if mp[p] < index:
                index = mp[p]
                c = p
    return c

if __name__ == "__main__":
    s = "geeksforgeeks"
    print(firstRep(s))  # Output: g
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static char firstRep(string s) {
        Dictionary<char, int> map = new Dictionary<char, int>();
        char c = '#';
        int index = int.MaxValue;

        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[] args) {
        string s = "geeksforgeeks";
        Console.WriteLine(firstRep(s)); // Output: g
    }
}
JavaScript
function firstRep(s) {
    let map = new Map();
    let c = '#';
    let index = Number.MAX_SAFE_INTEGER;

    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;
}

// Driver Code
const s = "geeksforgeeks";
console.log(firstRep(s)); // Output: g

Output
g
Comment