HomeLeetcode387. First Unique Character in a String - Leetcode Solutions

387. First Unique Character in a String – Leetcode Solutions

Description

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Examples:

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

Solution in Python

Approach

  1. Count Frequency of Each Character:
    • Use a dictionary (or a Counter from the collections module) to count the frequency of each character in the string.
  2. Identify the First Unique Character:
    • After counting the frequencies, iterate through the string and, for each character, check if its frequency is 1.
    • Return the index of the first character with frequency 1.
  3. Handle the Case of No Unique Characters:
    • If no characters have a frequency of 1, return -1.
Python
class Solution:
    def firstUniqChar(self, s: str) -> int:
        # Step 1: Count the frequency of each character
        char_count = Counter(s)
        
        # Step 2: Iterate over the string to find the first character with frequency 1
        for index, char in enumerate(s):
            if char_count[char] == 1:
                return index  # Return the index of the first unique character
        
        # Step 3: If no unique character found, return -1
        return -1

Detailed Explanation

  1. Counting Frequencies:
    • We use Counter(s) to get a dictionary where the keys are characters, and the values are the counts of those characters in s. This takes O(n) time, where nnn is the length of the string.
  2. Finding the First Unique Character:
    • We loop through each character in s along with its index. For each character, we check if its count in char_count is 1. The first character that meets this criterion is the first unique character, so we return its index.
    • This step also takes O(n) time, as we iterate through the string once.
  3. Returning -1 if No Unique Character Exists:
    • If no character has a frequency of 1 by the end of the loop, return -1.

Solution in C++

C++
class Solution {
public:
    int firstUniqChar(string s) {
        // Step 1: Create a hash map to store the frequency of each character.
        unordered_map<char, int> frequencyMap;
        
        // Step 2: Traverse the string and count the frequency of each character.
        for (char c : s) {
            frequencyMap[c]++;
        }
        
        // Step 3: Traverse the string again to find the first character with a frequency of 1.
        for (int i = 0; i < s.length(); i++) {
            // Check if the current character's frequency is 1
            if (frequencyMap[s[i]] == 1) {
                // If it is, return its index, as it is the first unique character
                return i;
            }
        }
        
        // Step 4: If no unique character is found, return -1
        return -1;
    }
};

Solution in Javascript

JavaScript
var firstUniqChar = function(s) {
    // Step 1: Create a map to store character counts
    const charCount = new Map();

    // Step 2: Loop through each character in the string and update its count in the map
    for (let char of s) {
        charCount.set(char, (charCount.get(char) || 0) + 1);
    }

    // Step 3: Loop through the string again to find the first character with count 1
    for (let i = 0; i < s.length; i++) {
        if (charCount.get(s[i]) === 1) {
            return i; // Return the index of the first non-repeating character
        }
    }

    // Step 4: If no unique character is found, return -1
    return -1;
};

Solution in Java

Java
class Solution {
    public int firstUniqChar(String s) {
        // Step 1: Create an array to store the frequency of each character
        // Since the string consists of only lowercase English letters, we can use an array of size 26
        // where each index represents a character ('a' - 'z').
        int[] charCount = new int[26];
        
        // Step 2: Count the occurrences of each character in the string
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            charCount[c - 'a']++; // Increment the count at the index corresponding to the character
        }
        
        // Step 3: Find the first character with a frequency of 1
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (charCount[c - 'a'] == 1) {
                // If we find a character with a frequency of 1, return its index
                return i;
            }
        }
        
        // Step 4: If no unique character is found, return -1
        return -1;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular