Skip to content

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 1Count every character first, in one pass.
Hint 2Then walk the string again and return the first index whose count is 1.
Hint 3s.count(ch) inside a loop scans the whole string each time: O(n²).

Learn the concepts

More Python problems

All Python problems