First Letter to Appear Twice LeetCode Solution

Problem – First Letter to Appear Twice LeetCode Solution

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.

First Letter to Appear Twice LeetCode Solution in C++

char repeatedCharacter(string s) {
    int cnt[26]{};
    for(char ch:s) if(++cnt[ch-'a']==2) return ch;
    return 0;
}

First Letter to Appear Twice LeetCode Solution in Java

public char repeatedCharacter(String s) {
    int cnt[]= new int[26];
    for(char ch:s.toCharArray()) if(++cnt[ch-'a']==2) return ch;
    return 'a';
}

First Letter to Appear Twice LeetCode Solution in Python

class Solution:
    def repeatedCharacter(self, s: str) -> str:
        occurences = defaultdict(int)
        for char in s:
            occurences[char] += 1
            if occurences[char] == 2:
                return char
First Letter to Appear Twice LeetCode Solution Review:

In our experience, we suggest you solve this First Letter to Appear Twice LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the First Letter to Appear Twice LeetCode Solution

Find on LeetCode

Conclusion:

I hope this First Letter to Appear Twice LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.