{x}
blog image

First Unique Character in a String

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 <= 105
  • s consists of only lowercase English letters.

Solution Explanation

The problem asks to find the index of the first non-repeating character in a given string. The solutions presented leverage the idea of counting character frequencies to efficiently solve this.

Approach:

  1. Character Counting: We first count the occurrences of each character in the input string. This can be done using a hash map (dictionary in Python) or an array (if we know the character set is limited, like lowercase English letters).

  2. First Unique Check: After counting, we iterate through the string again. For each character, we check its count from the frequency map. If the count is 1 (meaning it's unique), we return its index.

  3. No Unique Character: If we finish iterating the string without finding a unique character, it means there's no non-repeating character, so we return -1.

Time Complexity Analysis:

  • Character Counting: The first loop iterates through the string once, which takes O(n) time, where n is the length of the string.
  • First Unique Check: The second loop also iterates through the string once, taking O(n) time.
  • Overall: The dominant operations are the two linear iterations. Therefore, the overall time complexity is O(n).

Space Complexity Analysis:

  • The space complexity depends on the size of the character frequency map.
    • If we use a hash map, the worst-case space complexity is O(n) if all characters are unique. However, if the character set is limited (like only lowercase English letters), we can use a fixed-size array of size 26, resulting in O(1) space complexity.

Code Explanation (Python):

from collections import Counter
 
class Solution:
    def firstUniqChar(self, s: str) -> int:
        cnt = Counter(s)  #Efficient character counting using Counter
        for i, c in enumerate(s):
            if cnt[c] == 1:
                return i
        return -1

The Counter object from the collections module efficiently counts the frequency of each character in the string. The code then iterates through the string, checking the count of each character in cnt. If the count is 1, it means that's the first unique character and its index is returned.

Code Explanation (Java):

class Solution {
    public int firstUniqChar(String s) {
        int[] cnt = new int[26]; // Array to store character counts (lowercase English letters only)
        int n = s.length();
        for (int i = 0; i < n; ++i) {
            ++cnt[s.charAt(i) - 'a']; //Efficiently maps character to array index
        }
        for (int i = 0; i < n; ++i) {
            if (cnt[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}

This Java code uses an integer array cnt of size 26 to store the counts of each lowercase English letter. The character's ASCII value is used to calculate its index in the array. The rest of the logic is the same as the Python version.

The other language solutions follow a similar approach with minor syntactic differences to adapt to the respective language features. All maintain the O(n) time and O(1) space complexity (because we're dealing with only lowercase English alphabets).