46. First Non-Repeating Character
Difficulty: Easy · Topic: DSA for data engineers
Write first_unique(s): return the index of the first character that appears exactly once in s, or -1 if there is none. Upper and lower case are different characters. It must be O(n): strings can be 300,000 characters long.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
first_unique("leetcode")Expected: 0
Hints
Hint 1
Count every character first, in one pass.Hint 2
Then walk the string again and return the first index whose count is 1.Hint 3
s.count(ch) inside a loop scans the whole string each time: O(n²).Learn the concepts
- Lists, dicts and sets: what each operation costs · 7 min read. Pick the container from the question, and why a set turns an hour-long loop into a second.
More Python problems
- Two Sum · Easy
- Valid Brackets · Easy
- Group Anagrams · Medium
- Longest Substring Without Repeats · Medium
- Top K Frequent with a Heap · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard