LeetCode 2351: First Letter to Appear Twice Solution
Master LeetCode problem 2351 (First Letter to Appear Twice), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2351. First Letter to Appear Twice
Problem Explanation
Explanation
To solve this problem, we can iterate over the given string s and keep track of the indices at which we have seen each letter. We can use a hashmap to store the latest index of each letter. As we iterate through the string, we update the index of the current letter in the hashmap. If we encounter a letter that is already present in the hashmap, we check if the index is less than the previously stored index. If it is less, we update the index. Finally, we return the letter with the smallest index value of its second occurrence.
- Time complexity: O(n) where n is the length of the input string
s. - Space complexity: O(1) since the hashmap will contain at most 26 lowercase English letters.
Solution Code
class Solution {
public char firstLetterToAppearTwice(String s) {
char result = ' ';
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if (map.containsKey(current)) {
if (result == ' ' || map.get(current) < map.get(result)) {
result = current;
}
} else {
map.put(current, i);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2351 (First Letter to Appear Twice)?
This page provides optimized solutions for LeetCode problem 2351 (First Letter to Appear Twice) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2351 (First Letter to Appear Twice)?
The time complexity for LeetCode 2351 (First Letter to Appear Twice) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2351 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2351 in Java, C++, or Python.