Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find First Non-Repeating Character

Find the earliest character that occurs exactly once with Python. Students count first, scan order second, and stop at the first frequency-one character.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 8 of 14
find-first-non-repeating-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Find first non-repeating
5freq = {}
6for char in s:
7 freq[char] = freq.get(char, 0) + 1
8
9# Find first with count 1
10result = None
11for char in s:
12 if freq[char] == 1:
13 result = char
14 break
15
16if result:
17 print(f"First non-repeating: {result}")
18else:
19 print("No non-repeating character")

Output

Enter a string: hello
First non-repeating: h

In this one

  • Count before selecting
  • Follow original order
  • Stop at the first unique character

How it works

  1. 1

    Build complete frequencies.

  2. 2

    Scan s and find the first frequency-one character.

  3. 3

    Break and display it, or report no result.

Edge cases

Are spaces eligible?

Are spaces eligible?

Yes. They are counted like other characters.

What if every character repeats?

What if every character repeats?

No non-repeating character is printed.

What's going on

The dictionary pass builds complete frequencies. The next pass follows s itself rather than sorted keys, preserving the meaning of first.

For swiss, w is selected. A space can also be selected because it is a real character. result begins as None, and a successful character ends the scan with break. Empty or all-repeating input reaches the no-match message.

Are spaces eligible? Yes. They are counted like other characters.

What if every character repeats? No non-repeating character is printed.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why scan s after counting?

Pick an answer to check it.

Question 2

Are spaces eligible?

Pick an answer to check it.

Questions people ask

Are spaces eligible?

Yes. They are counted like other characters.

What if every character repeats?

No non-repeating character is printed.

Why scan s after counting?

To retain original first-appearance order.