Code Logo

First Repeated Character

Published at25 Jul 2026
Medium 0 views
Like0

Given a string, find the first character that repeats (appears more than once). Return the character that repeats first when scanning from left to right. If no character repeats, return an empty string.

Use a set to track characters that have been seen. Iterate through each character. If the character is already in the set, it's the first repeated character — return it. Otherwise, add it to the set and continue. If the loop completes without finding a repeat, return an empty string.

This is a hash set problem. Time complexity is O(n) and space complexity is O(k) where k is the character set size (at most 26 for lowercase letters, but the problem handles any 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
Recommendation Algorithm Flow for First Repeated Character

Solution Approach

function solution(s) {
  var seen = {};
  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if (seen[c]) return c;
    seen[c] = true;
  }
  return '';
}

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