

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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?
- Generating a unique random 10 character string using MySQL?
- Find repeated character present first in a string in C++
- 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?
- 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
- First Unique Number in C++
- Find the character in first string that is present at minimum index in second string in Python
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
Advertisements