##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2351.html

# 2351. First Letter to Appear Twice

• Difficulty: Easy.
• Related Topics: Hash Table, String, Counting.
• Similar Questions: Two Sum, First Unique Character in a String.

## Problem

Given a string s consisting of lowercase English letters, return the first letter to appear **twice**.

Note:

• A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.

• s will contain at least one letter that appears twice.

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 <= 100

• s consists of lowercase English letters.

• s has at least one repeated letter.

## Solution (Java, C++, Python)

• class Solution {
public char repeatedCharacter(String s) {
int n = s.length();
int[] hm = new int;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
hm[c - 'a']++;
if (hm[c - 'a'] > 1) {
return c;
}
}
return '0';
}
}

############

class Solution {
public char repeatedCharacter(String s) {
for (int i = 0;; ++i) {
char c = s.charAt(i);
if ((mask >> (c - 'a') & 1) == 1) {
return c;
}
mask |= 1 << (c - 'a');
}
}
}

• class Solution:
def repeatedCharacter(self, s: str) -> str:
for c in s:
i = ord(c) - ord('a')
if mask >> i & 1:
return c

############

# 2351. First Letter to Appear Twice
# https://leetcode.com/problems/first-letter-to-appear-twice/

class Solution:
def repeatedCharacter(self, s: str) -> str:
seen = set()

for x in s:
if x in seen:
return x


• class Solution {
public:
char repeatedCharacter(string s) {
for (int i = 0;; ++i) {
if (mask >> (s[i] - 'a') & 1) {
return s[i];
}
mask |= 1 << (s[i] - 'a');
}
}
};

• func repeatedCharacter(s string) byte {
for i := 0; ; i++ {
return s[i]
}
mask |= 1 << (s[i] - 'a')
}
}

• function repeatedCharacter(s: string): string {
for (const c of s) {
const i = c.charCodeAt(0) - 'a'.charCodeAt(0);
if (mask & (1 << i)) {
return c;
}
}
return ' ';
}


• impl Solution {
pub fn repeated_character(s: String) -> char {
for &c in s.as_bytes() {
if mask & 1 << (c - b'a') as i32 != 0 {
return c as char;
}
mask |= 1 << (c - b'a') as i32;
}
' '
}
}



Explain:

nope.

Complexity:

• Time complexity : O(n).
• Space complexity : O(n).