Computer >> Computer tutorials >  >> Programming >> Python

Python program to Find the first non-repeating character from a stream of characters?


In this section we are going to find the first unique or non-repeating character from a string or stream of characters. There are multiple ways to solve this problem. We will try to create two different program for the same stream of characters.

Method 1: Using function

def firstNonRepeatingChar(str1):
   char_order = []
   counts = {}
   for c in str1:
      if c in counts:
         counts[c] += 1
      else:
         counts[c] = 1
         char_order.append(c)
   for c in char_order:
      if counts[c] == 1:
      return c
   return None

print(firstNonRepeatingChar('PythonforallPythonMustforall'))
print(firstNonRepeatingChar('tutorialspointfordeveloper'))
print(firstNonRepeatingChar('AABBCC'))

Result

M
u
None

Above program give O(n) solution. In above program we first loop through the string once. Once we find a new character, we store it in counts object with a value of 1 and append it to char_order. When we come across a repeated character, we increment the value of counts by 1. Finally, we loop through char_order until we find a character with a value of 1 in char_order and return it.

Method 2: Using while loop

s = "tutorialspointfordeveloper"
while s != "":
   slen0 = len(s)
   ch = s[0]
   s = s.replace(ch, "")
   slen1 = len(s)
   if slen1 == slen0-1:
      print ("First non-repeating character is: ",ch)
      break;
   else:
   print ("No Unique Character Found!")

Result

First non-repeating character is: u