First One-of-a-Kind Character
Easy · Arrays & Hashing · about 10 min
A ticket machine prints one character per seat on a long strip, like "racecars". Find the position of the first character that appears exactly once in the whole string. If every character repeats, return -1.
shas 0 to 100,000 characters.- Upper and lower case are different characters (
"a"is not"A"). - Positions start at 0.
Examples:
first_lonely_char("racecars") → 3 ("e" is the first character that appears only once)
first_lonely_char("abba") → -1
Hints
- You only know a character is unique after you have seen the whole string.
- First pass: count every character. Second pass: find the first one with count 1.
Learn the pattern first: the Arrays & Hashing lesson.
More Arrays & Hashing problems
- First Badge Scanned Twice (Easy)
- Spell It With Tiles (Easy)
- Two Parcels, Exact Load (Easy)
- Group Words With the Same Letters (Medium)
- Trending Hashtags (Medium)
- Longest Streak of Floors (Medium)
- Everyone Else's Product (Medium)
- First Free Ticket Number (Hard)
- Most Lamp Posts in One Line (Hard)