Leetcode 2351. First Letter to Appear Twice
LeetCode Problem 2351: First Letter to Appear Twice
Given a string s
consisting of lowercase English letters, return the first letter to appear twice in the string.
Input: s = "abccbaacz"
Output: c
Input: s = "abcdd"
Output: d
s
will have a length from 1 to 100.s
consists of lowercase English letters only.#include <iostream>
#include <unordered_set>
#include <string>
char repeatedCharacter(const std::string& s) {
std::unordered_set<char> seen;
for (char ch : s) {
if (seen.find(ch) != seen.end()) {
return ch;
}
seen.insert(ch);
}
return '\0'; // This should never be reached due to problem constraints.
}
int main() {
std::string s1 = "abccbaacz";
std::string s2 = "abcdd";
std::cout << "First repeated character in \"" << s1 << "\" is: " << repeatedCharacter(s1) << std::endl;
std::cout << "First repeated character in \"" << s2 << "\" is: " << repeatedCharacter(s2) << std::endl;
return 0;
}
s
once, where n
is the length of the string.This problem is efficiently solved using the above approach and handles all given constraints per the problem statement.
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?