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 = "leetcode"
Output: 0
Explanation:
The character 'l' at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Constraints:
1 <= s.length <= 105s consists of only lowercase English letters.This approach employs a hash map to store the frequency of each character in the string. Then, by iterating through the string again, we can find the first character with a frequency of 1 and return its index. If no such character is found, we return -1.
The function firstUniqChar tracks the frequency of each character in the string using an integer array. The first loop fills up the frequencies, and the second loop finds the first character with a frequency of one, returning its index. If no such character is present, it returns -1.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string, as we traverse through the string twice.
Space Complexity: O(1), because the array size is constant (26 letters of the English alphabet).
This approach involves iterating through the input string two times without using any auxiliary space like a hash map or dictionary. In the first iteration, we use an array to count the occurrences of each character. In the second iteration, we check for the first character that appears only once by referring to the count array. We conclude by returning its index or -1 if no such character is found.
The C solution involves a simple integer array of size 26, corresponding to each lowercase letter, and populating it with frequencies of the characters present. By going over the string a second time, the index of the first non-repeating character is identified.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Approach 1: Using a Frequency Map | Time Complexity: O(n), where n is the length of the string, as we traverse through the string twice. |
| Approach 2: Using Two Iterations Without Hash Map | Time Complexity: O(n) |
First Unique Character in a String • Kevin Naughton Jr. • 88,593 views views
Watch 9 more video solutions →Practice First Unique Character in a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor