Given a string s consisting of lowercase English letters, return the first letter to appear twice.
Note:
- A letter
aappears twice before another letterbif the second occurrence ofais before the second occurrence ofb. swill contain at least one letter that appears twice.
First Letter to Appear Twice LeetCode Contest
Example 1:
Input: s = "abccbaacz" Output: "c" Explanation: The letter 'a' appears on the indexes 0, 5 and 6. The letter 'b' appears on the indexes 1 and 4. The letter 'c' appears on the indexes 2, 3 and 7. The letter 'z' appears on the index 8. The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
Input: s = "abcdd" Output: "d" Explanation: The only letter that appears twice is 'd' so we return 'd'.
Constraints:
2 <= s.length <= 100sconsists of lowercase English letters.shas at least one repeated letter.
Solution
class Solution {
public:
char repeatedCharacter(string s) {
vector<bool> v(26);
for(char c:s){
if(v[c-'a'])return c;
v[c-'a']=true;
}
return 'a';
}
};class Solution:
def repeatedCharacter(self, s: str) -> str:
occurences = defaultdict(int)
for char in s:
occurences[char] += 1
if occurences[char] == 2:
return charclass Solution {
public char repeatedCharacter(String s) {
Set<Character> seen = new HashSet<>();
for(int i = 0; i < s.length(); i++){
if(seen.contains(s.charAt(i))){
return s.charAt(i);
}
seen.add(s.charAt(i));
}
return '#';
}
}Happy Learning – If you require any further information, feel free to contact me.
![[Solved] First Letter to Appear Twice LeetCode Contest Problem [Solved] First Letter to Appear Twice LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-First-Letter-to-Appear-Twice-LeetCode-Contest-Problem.png)
![[Solved] Maximum Difference by Remapping a Digit with Java](https://realcoder.techss24.com/wp-content/uploads/2023/02/Solved-Maximum-Difference-by-Remapping-a-Digit-with-Java-300x169.png)

![[Solved] Count Special Integers LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/08/Solved-Count-Special-Integers-LeetCode-Contest-Problem-300x200.png)