
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
First Unique Character in a String in Python
Suppose we have a string and we have to find the first unique character in the string. So if the string is like “people”, the first letter whose occurrence is one is ‘o’. So the index will be returned, that is 2 here. If there is no such character, then return -1.
To solve this, we will follow these steps −
- create one frequency map
- for each character c in the string, do
- if c is not in frequency, then insert it into frequency, and put value 1
- otherwise, increase the count in frequency
- Scan the frequency map, if the value of a specific key is 1, then return that key, otherwise return -1
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ frequency = {} for i in s: if i not in frequency: frequency[i] = 1 else: frequency[i] +=1 for i in range(len(s)): if frequency[s[i]] == 1: return i return -1 ob1 = Solution() print(ob1.firstUniqChar("people")) print(ob1.firstUniqChar("abaabba"))
Input
"people" "abaabba"
Output
2 -1
- Related Articles
- Find the index of the first unique character in a given string using C++
- A unique string in Python
- Python program to check if a string contains any unique character
- How to find a unique character in a string using java?
- Find repeated character present first in a string in C++
- Generating a unique random 10 character string using MySQL?
- Find the first repeated character in a string using C++.
- Return index of first repeating character in a string - JavaScript
- Select all except the first character in a string in MySQL?
- Find the character in first string that is present at minimum index in second string in Python
- How to find the first character of a string in C#?
- Remove all except the first character of a string in MySQL?
- Finding the first non-repeating character of a string in JavaScript
- Program to find the index of first Recurring Character in the given string in Python
- Count occurrences of a character in string in Python

Advertisements