First Repeated Character
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
l is the first character that repeats
No repeating characters
a repeats first at position 0 and 1
a at end repeats the first a
Empty string
Algorithm Flow

Solution Approach
Best Answers
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 "";
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
