Member-only story
Python Coding Question #6
First Non-Repeating Character in a String
Question:
Write a python program to find the first non-repeating character in a string
Lets see the solutions:
- Using Counter class from collections module
from collections import Counter
def first_non_repeating_char(string):
char_counts = Counter(string)
for char in string:
if char_counts[char] == 1:
return char
return None
# Example usage:
string = "today"
result = first_non_repeating_char(string)
print(result)
# Output - tHere in the solution, we first import the Counter class from collections module to efficiently count character frequencies and then create the Counter object char_counts to store the frequency of each character in the string and then iterate over each character in the string and check its frequency in the char_counts dictionary. If the frequency of a character is 1, it means it’s the first non-repeating character, so we return the unique first non-repeated character or else we return None.
2. Using a generator expression in one line
def first_non_repeating_char(s):
return next((char for char in s if s.count(char) == 1), None)
print(first_non_repeating_char('today')) # Output - t…




