Leetcode 2351. First Letter to Appear Twice
Given a string s
consisting of lowercase English letters, return the first letter to appear twice.
Assumption: The string is always non-empty and there is always at least one character that appears twice.
Understood: Yes, return the first character that appears twice.
public class Solution {
public char repeatedCharacter(String s) {
Set<Character> seen = new HashSet<>();
for (char c : s.toCharArray()) {
if (seen.contains(c)) {
return c; // Return the first character that appears twice
}
seen.add(c);
}
// As per problem constraints, we should never reach here.
throw new IllegalArgumentException("No character appears twice in the given string");
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example Test Cases
System.out.println(solution.repeatedCharacter("abccbaacz")); // Outputs 'c'
System.out.println(solution.repeatedCharacter("abcddcba")); // Outputs 'd'
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?