Similar Problems

Similar Problems not available

First Letter To Appear Twice - Leetcode Solution

Companies:

LeetCode:  First Letter To Appear Twice Leetcode Solution

Difficulty: Easy

Topics: string hash-table bit-manipulation  

The First Letter To Appear Twice problem on Leetcode asks the following question:

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

To solve this problem, we can iterate through the string s and keep track of the count of each character in a hash table. Then, we can iterate through the hash table to find the first character that has a count of 2. If we find such a character, we can return its index in the original string. If we reach the end of the string without finding such a character, we can return -1.

Here is the detailed solution:

def firstUniqChar(s: str) -> int:
    # initialize hash table
    char_count = {}

    # iterate through string to count characters
    for char in s:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1

    # iterate through hash table to find first character with count 2
    for i in range(len(s)):
        if char_count[s[i]] == 2:
            return i

    # if no character with count 2 was found, return -1
    return -1

The time complexity of this solution is O(N), where N is the length of the input string. The space complexity is O(K), where K is the number of unique characters in the input string.

First Letter To Appear Twice Solution Code

1