Python Program to Find First Non Repeating Character in a String

Non Repeating Character in a String in Python

Here on this page, we will learn how to create a program to Find First Non Repeating Character in a String in Python Language.

Example :

  • Input : “PREPINSTA”
  • Output : First non-repeating character is : R
Non Repeating Character in a String in Python

Methods Discussed :

  • Method 1 : Naïve Approach
  • Method 2 : Using Two string Traversal method.
  • Method 3 : Using In-Built function ( Count ), single traversal.

Let’s discuss them one by one in brief,

Algorithm ( Method 1 ) :

  • Declare a variable say flag, that will store to 1 if the duplicate element is founded.
  • Start iterating over the string str,
  • Set flag =0;
  • Run a loop from index 0 to len
  • Check if(str[i]==str[j] && (i!=j))
  • Then, set flag =1; and break the loop
  • Check if(flag==0)
  • Print the character.
  • At last if(flag==1), print “No non-repeating character”

Python Code

Run
str = "PREPINSTA"
l = len(str)
flag = 0
for i in range(l):
    flag = 0
    for j in range(l):
        if str[i] == str[j] and i != j:
            flag = 1
            break
    if flag == 0:
        print("First non-repeating character is :", str[i])
        break

if flag == 1:
    print("No non-repeating character")

Output

First non-repeating character is : R

Algorithm ( Method 2 ) :

  • Make a hash map that maps the characters to their frequency values.
  • Using a pointer, traverse the given string.
  • Increase the current character’s count in the hash map.
  • Now go back over the string and see if the current character has frequency=1.
  • Continue the traverse if the frequency is more than one.
  • If the loop is not broken, print the current character as the answer.
  • break the loop and print the current character as the answer.

Python Code

Run
NO_OF_CHARS = [0] * 256


def getCharCountArray(str):
    for i in str:
        NO_OF_CHARS[ord(i)] += 1


def firstNonRepeating(str):
    getCharCountArray(str)
    for i in range(len(str)):
        if NO_OF_CHARS[ord(str[i])] == 1:
            return i
    return -1


str = "PREPINSTA"
index = firstNonRepeating(str)
if index == -1:
    print("No non-repeating character")
else:
    print("First non-repeating character is :", str[index])

Output

First non-repeating character is : R

Algorithm ( method 3 ) :

  • Initialize a flag zero if the flag is zero till the end of the program which means there are no non-repeating characters in the given string
  • For each character in string check count of its occurrence in string where ever it is zero print that character and make flag 1

Python Code

Run
str = "PREPINSTA"
flag = 0
for i in str:
    if str.count(i) == 1:
        print("First non-repeating character is :", i)
        flag = 1
        break
if flag == 0:
    print("No non-repeating character")

Output

First non-repeating character is : R

For similar Questions click on the given button.