Find the First Non-Repeating Character in a String
Implement firstUniqChar
Given a string
s, find the first character that never repeats anywhere else in the string, and return its index. If every character repeats, return -1.
Checking each character against every other character works, but it's quadratic. The faster approach counts every character's frequency in one pass, then makes a second pass in order and returns the index of the first character whose frequency is exactly 1 — the first one that was never seen again.
Example 1:
Input: s = "swiss"
Output: 1
Example 2:
Input: s = "aabb"
Output: -1
Example 3:
Input: s = "leetcode"
Output: 0
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 10⁵ - ●
s consists only of lowercase English letters
s =
swiss