First character seen once
Given a string, find the position of the first character that appears exactly once. Upper and lower case count as different characters.
first_unique("stress") # 1, the "t"
first_unique("aabb") # -1Approach
A nested loop that compares each character against all others takes quadratic time. Two passes with a dict is better:
- The first pass counts every character.
- The second pass walks the string in order and stops at the first count of 1.
collections.Counter does the counting:
from collections import Counter
Counter("aab") # Counter({'a': 2, 'b': 1})Walk the original string in the second pass, because that is where the order you need lives. Dict order alone would also work here, but the string makes the intent clear and gives you the index.
Your task
Write first_unique(text) returning the index of the first character that occurs exactly once, or -1 if there is none.
The explanation opens here once every check passes.