KatInterview

387. First Unique Character in a String

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the index of the first character in a given string that appears only once. If no such character exists, we should return -1. The string is guaranteed to contain only lowercase English letters.

Solution

First Unique Character in a String in Python

import collections

class Solution:
    def firstUniqChar(self, s: str) -> int:
        # First pass: use collections.Counter to build a frequency map.
        # This is a highly efficient way to count hashable objects.
        counts = collections.Counter(s)
        
        # Second pass: find the first unique character.
        # Enumerate through the string to get both index and character.
        for i, char in enumerate(s):
            # Check the frequency of the character.
            if counts[char] == 1:
                # If the count is 1, it's the first unique character. Return its index.
                return i
        
        # If the loop completes, no unique character was found.
        return -1

First Unique Character in a String in Java

class Solution {
    public int firstUniqChar(String s) {
        // Use an array of size 26 as a frequency map for lowercase English letters.
        int[] counts = new int[26];
        
        // First pass: build the frequency map.
        // Iterate through the string and count each character's occurrences.
        for (int i = 0; i < s.length(); i++) {
            counts[s.charAt(i) - 'a']++;
        }
        
        // Second pass: find the first unique character.
        // Iterate through the string again.
        for (int i = 0; i < s.length(); i++) {
            // Check the frequency of the character at the current index.
            if (counts[s.charAt(i) - 'a'] == 1) {
                // If the count is 1, it's the first unique character. Return its index.
                return i;
            }
        }
        
        // If the loop completes, no unique character was found.
        return -1;
    }
}

First Unique Character in a String in C++

class Solution {
public:
    int firstUniqChar(string s) {
        // Use a vector of size 26 as a frequency map for lowercase English letters.
        // Initialize all counts to 0.
        vector<int> counts(26, 0);
        
        // First pass: build the frequency map.
        // Iterate through the string and count each character's occurrences.
        for (char c : s) {
            counts[c - 'a']++;
        }
        
        // Second pass: find the first unique character.
        // Iterate through the string again, this time with indices.
        for (int i = 0; i < s.length(); ++i) {
            // Check the frequency of the character at the current index.
            if (counts[s[i] - 'a'] == 1) {
                // If the count is 1, it's the first unique character. Return its index.
                return i;
            }
        }
        
        // If the loop completes, no unique character was found.
        return -1;
    }
};

First Unique Character in a String in TypeScript

function firstUniqChar(s: string): number {
    // Use an array of size 26 as a frequency map for lowercase English letters.
    const counts = new Array(26).fill(0);
    const aCode = 'a'.charCodeAt(0);

    // First pass: build the frequency map.
    // Iterate through the string and count each character's occurrences.
    for (let i = 0; i < s.length; i++) {
        counts[s.charCodeAt(i) - aCode]++;
    }

    // Second pass: find the first unique character.
    // Iterate through the string again.
    for (let i = 0; i < s.length; i++) {
        // Check the frequency of the character at the current index.
        if (counts[s.charCodeAt(i) - aCode] === 1) {
            // If the count is 1, it's the first unique character. Return its index.
            return i;
        }
    }

    // If the loop completes, no unique character was found.
    return -1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.