Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Constraints
1 <= s.length <= 10^5
s
consists of only lowercase English letters.
Example
-
Input: s = "programming"
Output: 0
Explanation: The character 'p'
at index 0
is the first non-repeating character.
-
Input: s = "swiss"
Output: 0
-
Input: s = "aabb"
Output: -1
Approach
Brute Force Approach
Idea: Compare each character of the string with all other characters to determine its frequency. Return the index of the first character with a frequency of 1
.
Steps
- Loop through each character in the string.
- For each character, loop through the string to count its occurrences.
- If the count of the character is
1
, return its index.
- If no character has a count of
1
, return -1
.
Time & Space Complexity
-
Time Complexity: O(n²)
For each character, we iterate through the string to count occurrences.
-
Space Complexity: O(1)
No additional data structures are used.
Code Snippet
Dry Run
Input: s = "loveleetcode"
- For character
'l'
at index 0
:
- Count its occurrences:
1
.
- Return index
0
.
Optimized Approach Using a Queue
Idea: Use a queue to store characters along with their indices as they are encountered in the string. Simultaneously, use a hash map to track the frequency of each character. This allows efficient traversal and checking for the first unique character.
Steps
-
Initialize:
- A queue to store characters with their indices.
- A hash map to track the frequency of each character.
-
First Pass:
- Loop through the string.
- Update the frequency of each character in the hash map.
- Add each character with its index to the queue.
-
Second Pass:
- While the queue is not empty:
- Check the frequency of the character at the front of the queue.
- If the frequency is
1
, return its index.
- Otherwise, dequeue it (remove from the front).
- If the queue becomes empty, return
-1
(no unique character found).
Time & Space Complexity
- Time Complexity: O(n)
- First pass processes the string in O(n).
- Second pass dequeues each element once, also O(n).
- Space Complexity: O(n)
- The queue and hash map both store up to
n
elements.
Code Snippet
Dry Run
Input: s = "loveleetcode"
-
Populate the hash map and queue:
- Hash map:
{ 'l': 1, 'o': 1, 'v': 1, 'e': 4, 't': 1, 'c': 1, 'd': 1 }
- Queue:
[ ['l', 0], ['o', 1], ['v', 2], ['e', 3], ['e', 4], ['t', 5], ['c', 6], ['d', 7] ]
-
Process the queue:
'l'
at index 0
has a frequency of 1
.
- Return
0
.
Complexity Analysis
Operation | Optimized Using Queue |
---|
Time Complexity | O(n) |
Space Complexity | O(n) |
Conclusion
Using a queue introduces structure to the problem, allowing efficient processing of the first unique character while maintaining an intuitive approach. This method combines the power of a hash map for quick frequency lookups and a queue for orderly traversal of characters.