Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to Find the first non-repeating character from a stream of characters?
In this article, we will find the first non-repeating character from a stream of characters. A non-repeating character is one that appears exactly once in the string. Let's say the following is our input ?
thisisit
The following should be our output displaying first non-repeating character ?
h
Using While Loop
We will find the first non-repeating character by comparing each character with others using a while loop. This approach removes all occurrences of each character and checks if only one was removed ?
# String
my_str = "thisisit"
# Looping
while my_str != "":
original_len = len(my_str)
char = my_str[0]
my_str = my_str.replace(char, "")
new_len = len(my_str)
if new_len == original_len - 1:
print("First non-repeating character =", char)
break
else:
print("No unique character found!")
First non-repeating character = h
Using a Custom Function with Dictionary
We can create a custom function that uses a dictionary to count character frequencies and a list to maintain the order of first occurrence ?
# Custom function
def find_first_non_repeating(my_str):
char_order = []
counts = {}
# Count frequencies and track order
for char in my_str:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
char_order.append(char)
# Find first character with count 1
for char in char_order:
if counts[char] == 1:
return char
return None
result = find_first_non_repeating('thisisit')
print("First non-repeating character =", result)
First non-repeating character = h
Using Counter from Collections Module
The Counter from the collections module provides a convenient way to count character frequencies. This approach is more concise and efficient ?
from collections import Counter
def find_non_repeating_counter(my_str):
# Count character frequencies
freq = Counter(my_str)
# Find first character with frequency 1
for char in my_str:
if freq[char] == 1:
return char
return None
# Driver code
my_str = "thisisit"
result = find_non_repeating_counter(my_str)
print("First non-repeating character =", result)
h
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| While Loop | O(n²) | O(1) | Simple understanding |
| Custom Function | O(n) | O(n) | Maintaining order |
| Counter | O(n) | O(n) | Clean, readable code |
Conclusion
The Counter method is most efficient and readable for finding the first non-repeating character. The custom function approach provides good control over the process, while the while loop method is educational but less efficient for larger strings.
