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.
1# Take string input2s = input("Enter a string: ")34# Find first non-repeating5freq = {}6for char in s:7 freq[char] = freq.get(char, 0) + 189# Find first with count 110result = None11for char in s:12 if freq[char] == 1:13 result = char14 break1516if 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
Build complete frequencies.
- 2
Scan s and find the first frequency-one character.
- 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.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum