You are given a string s of lowercase letters. Find the first letter in it that appears exactly once in the whole string.
Return that letter's index. If every letter appears two or more times, return -1.
Example 1
Input: s = "swiss" Output: 1 Why: s appears 3 times; w at index 1 appears once
2 more examples and the constraints
Example 2
Input: s = "racecar" Output: 3 Why: r, a and c each appear twice; e appears once
Example 3
Input: s = "xxyy" Output: -1 Why: every letter has a twin
Constraints
- 1 ≤ length of s ≤ 100,000
- s holds only lowercase English letters, a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every letter against all othersO(n²)
- Count, then scanO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 letters | Verdict |
|---|---|---|---|
| Check every letter against all others | O(n²) | Mention it, then move on | |
| Count, then scan | O(n) | Best; two quick passes |
n = the length of s.
Edge cases to test
- One letter. "q" is unique by itself: return 0.
- No unique letter. "xxyy" and "mm" return -1.
- Unique letter last. "ppqqz" returns 4; make sure the scan reaches the end.
- Twin far away. In "abcdefgha" the first a has its twin at the very end, so the answer is 1, not 0.
Common mistakes
- Only comparing a letter with the ones after it, so in "abab" the second a looks unique.
- Looping over the count map in pass 2, which can return a unique letter that is not the first one in s.
- Returning the letter instead of its index, or 0 instead of -1 when there is none.
How to talk through it
- 1Clarify. Only lowercase letters? Return the index, and -1 if there is no unique letter?
- 2Give the brute force. For each letter, scan for a twin; O(n²) for 100,000 letters is too slow.
- 3Split it into two passes. Uniqueness needs the whole string, so count first, then scan in order.
- 4Code it with 26 counters. Index with ch − 'a'; the memory is fixed, so the space is O(1).
- 5Test out loud. Run "swiss", "xxyy" and "q", and check 1, -1 and 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?