54. First Solo Letter
A text editor highlights the first letter in a line that appears only once in the whole line. You are given a string s of lowercase letters. Return the zero-based index of the first character of s that occurs exactly once in s. If every letter occurs more than once, return -1.
Do not compare every pair of positions. Make one pass to count how often each letter appears and a second pass to find the first position whose letter has a count of one.
Example 1
- Input:
- s = "swiss"
- Output:
- 1
- Explanation:
The letters s and i repeat, and w occurs once at index 1, so the answer is 1.
Example 2
- Input:
- s = "aabb"
- Output:
- -1
- Explanation:
Every letter occurs twice, so there is no solo letter and the answer is -1.
Constraints
1 ≤ s.length ≤ 105
s contains only lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)