First Unique Character in a String | LeetCode 387 | Python | Solution

This problem is pretty straightforward. Click here to see the problem.

Problem Overview

The problem description is one line and pretty simple. It says that we have to find the first unique character from a string and return the index of that character. In the given String, all characters will be English lowercase letters.

Suppose the given string is: 'abc'. We can see here that the three characters are unique. So, here a is the first no-repeating character, and the index of this character is 0.

Let’s assume that the given string is: 'aabc'. Here a is repeated two times, but b and c are unique. So, b is the first non-repeating character, and the index of b is 2.

Coding Part

There are many ways to solve a problem. So, I am going to solve this problem using HashTable. We will use HashTable is for tracking the frequency of the character. We all know that in HashTable, we store data as a key-value pair. So character will be the key, and the times a character appears in the given string will be the value of that character. To do this, we will loop through the given string.

After that, we will check each of the characters’ frequency using the HashTable. If the value of a character is 1, we will return that character’s index. As the loop runs from start to end, we will get the first unique character’s index.

If there is no unique or non-repeating character in the given string, we will return -1.

Let’s see the solution in code.

class Solution:
    def firstUniqChar(self, s: str) -> int:
        frequency= {}
        for i in range(len(s)):
            if s[i] not in frequency:
                frequency[s[i]] = 1
                frequency[s[i]] += -1
        for i in range(len(s)):
            if frequency[s[i]] == 1:
                return i
        return -1

I hope you got the idea about the problem and the solution. If you submit this code, it will get accepted.