First Repeated Character
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
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
Use a set to track seen characters and return the first duplicate encountered.
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
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.
