The problem of finding the first unique character in a string is a popular coding interview question. Here you will be given a string, and you have to return the index of the first non-repeating character in the string as an output. So, if you want to know how to find the first unique character in a string, this article is for you. In this article, I will take you through how to find the first unique character in a string using Python.
First Unique Character in a String
In the problem of finding the first unique character in a string, you will be given a string as input. To solve this problem, you need to find the index of the first character in the string that is non-repeating in the string. And if there is no unique character, your output should return -1.
For example, look at the input and output of this problem shown below:
- Input: “amankharwal” | Output: 1 (index of m)
- Input: “aamm” | Output: -1 (no unique character found)
Finding the First Unique Character using Python
I hope you have understood what the problem of finding the first unique character in a string means. Now, below is how you can solve this problem using the Python programming language:
def firstUniqueChar(s): from collections import Counter count = Counter(s) for i , j in enumerate(s): if count[j] == 1: return i else: return -1 print(firstUniqueChar("amankharwal"))
Output: 1
So this is how you can find the first unique character in a string using Python. You can find many more practice questions for coding interviews solved and explained using Python here.
Summary
In the problem of finding the first unique character in a string, you will be given a string as input. To solve this problem, you need to find the index of the first character in the string that is non-repeating in the string. I hope you liked this article on finding the first unique character in a string using Python. Feel free to ask valuable questions in the comments section below.