You are given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 1:
Input: s = "neetcodeislove"
Output: 0Explanation: The character 'n' at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "neetcodeneet"
Output: 4Example 3:
Input: s = "baab"
Output: -1Constraints:
1 <= s.length <= 1,00,000s consists of only lowercase English letters.For each character in the string, we check if it appears anywhere else. If a character has no duplicate, it is unique. The first such character we find (going left to right) is our answer.
i in the string.i, compare it with every other character at index j.i != j), mark it as non-unique and break.i.-1.Instead of checking every pair of characters, we can count the frequency of each character in a single pass. Then, in a second pass, we find the first character whose count is exactly 1. This trades space for time.
1.-1.We can optimize the second pass by iterating over the hash map instead of the string. For each character, we store its first occurrence index. If the character appears again, we mark it as non-unique by setting its index to n (string length). Finally, we find the minimum index among all unique characters.
n.n, otherwise return -1.Since the string contains only lowercase letters, we can iterate through all 26 characters and find the first occurrence of each. If a character's first and last occurrence are the same index, it appears exactly once. We track the minimum such index across all characters.
res to the string length n.'a' to 'z':indexOf (or equivalent).lastIndexOf.res with the minimum.res if it's less than n, otherwise return -1.