- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the first non-repeating character from a stream of characters in Python
Suppose we have a stream of characters, or we can consider a string and we have to find the first non-repeating 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 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 specific key is 1, then return that key, otherwise return -1
Example
Let us see the following implementation to get 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
- Python program to Find the first non-repeating character from a stream of characters?
- Java program to Find the first non-repeating character from a stream of characters
- Finding first non-repeating character JavaScript
- Finding the first non-repeating character of a string in JavaScript
- How to find its first non-repeating character in a given string in android?
- First non-repeating character using one traversal of string in C++
- Find first repeating character using JavaScript
- Find the last non repeating character in string in C++
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- Return index of first repeating character in a string - JavaScript
- Finding the index of the first repeating character in a string in JavaScript
- First non-repeating in a linked list in C++
- Queries to find the last non-repeating character in the sub-string of a given string in C++
- Detecting the first non-repeating string in Array in JavaScript
- Write a program to find the first non-repeating number in an integer array using Java?

Advertisements