Editor

Python Program to Find the First Non-Repeating Character

Intermediate · Strings

The first non-repeating character of a string is the first character that appears only once in it. In "swiss" the letter s appears three times, so the answer is w. This is a common interview question, solved here with two passes over the string.

Program

first_non_repeating_character.py
text = "swiss" # or: text = input("Enter a string: ")
# First pass: count every character
counts = {}
for ch in text:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
# Second pass: the first character with a count of 1 is the answer
answer = None
for i, ch in enumerate(text):
if counts[ch] == 1:
answer = ch
position = i
break
print("String:", text)
if answer is None:
print("Every character repeats")
else:
print(f"First non-repeating character: '{answer}' at index {position}")
Output
String: swiss
First non-repeating character: 'w' at index 1

How it works

  1. The first loop counts how many times each character appears and stores the counts in a dictionary.
  2. The second loop goes through the string again, in its original order, and stops at the first character whose count is 1.
  3. enumerate() gives the index as well as the character, so the program can report the position too.
  4. If every character repeats, answer stays None and the program says so.
  5. Each loop reads the string only once, so the program stays fast even on very long strings.

Other ways to write it

Using Counter and next()

Using Counter and next()
from collections import Counter
for text in ["swiss", "aabbcdd", "racecar", "aabb"]:
counts = Counter(text)
first = next((ch for ch in text if counts[ch] == 1), None)
print(f"{text}: {first}")
Output
swiss: w
aabbcdd: c
racecar: e
aabb: None

next() takes the first value the generator produces, and its second argument, None, is returned when no character qualifies, as with "aabb".

Using count()

Using count()
text = "swiss"
for ch in text:
if text.count(ch) == 1:
print("First non-repeating character:", ch)
break
else:
print("Every character repeats")
Output
First non-repeating character: w

The else of a for loop runs only when the loop ends without break. This version is shorter, but count() rescans the string for every character, which is slow for long strings.

Try it yourself

Change the program to find the first character that does repeat, such as s in "swiss".

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises