Code Logo

First Repeated Character

Published at25 Jul 2026
Medium 1 views
Like0

Given a string, find the first character that appears more than once. Return the first repeated character. If no character repeats, return an empty string.

For example, in "hello", the first repeated character is 'l' (appears at positions 2 and 3). In "abcdef", no character repeats — return "". In "aabbcc", the first repeated is 'a' (appears at positions 0 and 1).

Finding repeated characters is used in password strength checking, data validation, and duplicate detection. It teaches the use of a tracking data structure (like a set or frequency map) to efficiently detect duplicates in a single pass.

The solution uses a set to track characters seen so far. Iterate through the string character by character. If the current character is already in the set, return it as the first repeated character. Otherwise, add it to the set and continue. If the loop finishes without finding a repeat, return an empty string.

Edge cases include an empty string (return ""), a single character (return ""), all unique characters (return ""), and the first character being repeated later in the string (return that character).

Example Input & Output

Example 1
Input
"hello"
Output
"l"
Explanation

l is the first character that repeats

Example 2
Input
"abcdef"
Output
""
Explanation

No repeating characters

Example 3
Input
"aabbcc"
Output
"a"
Explanation

a repeats first at position 0 and 1

Example 4
Input
"abca"
Output
"a"
Explanation

a at end repeats the first a

Example 5
Input
""
Output
""
Explanation

Empty string

Algorithm Flow

Recommendation Algorithm Flow for First Repeated Character

Solution Approach

Use a set to track seen characters and return the first duplicate encountered.

function firstRepeat(s)
  seen = empty set
  for i = 0 to length(s) - 1
    if s[i] in seen then return s[i]
    add s[i] to seen
  return ""

Initialize an empty set to track characters that have been seen. Loop through each character in the string. If the character is already in the set, it is the first repeated character — return it immediately. Otherwise, add the character to the set and continue. If no repeats are found, return an empty string.

Time complexity is O(n), space complexity is O(k) where k is the number of unique characters in the alphabet.

Best Answers

java
class Solution {
    public String solution(String s) {
        java.util.Set<Character> seen=new java.util.HashSet<>();
        for(int i=0;i<s.length();i++){char c=s.charAt(i);
            if(seen.contains(c))return String.valueOf(c);
            seen.add(c);
        }return "";
    }
}