387. First Unique Character in a String

The First Unique Character in a String problem is a common algorithmic challenge where the goal is to find the index of the first non-repeating character in a given string. In this blog, we will explore the problem, understand the solution, and discuss the implementation details.

Problem Statement

Given a string s, we are required to find the index of the first non-repeating character. If there is no such character, we return -1.

For example, given:

s = "leetcode"

The first non-repeating character is ‘l’ at index 0.

Approach

To solve this problem efficiently, we can use an array to store the frequency of each character in the string. We iterate through the string to populate the frequency array. Once the frequency array is prepared, we traverse the string again to find the first character with a frequency of 1.

Solution

Let’s dive into the solution:

class Solution {
    public int firstUniqChar(String s) {
        int freq[] = new int[26];
        char c[] = s.toCharArray();
        for (int i = 0; i < c.length; i++) {
            freq[(int) (c[i] - 'a')]++;
        }
        for (int i = 0; i < c.length; i++) {
            if (freq[(int) (c[i] - 'a')] == 1) {
                return i;
            }
        }
        return -1;
    }
}

https://leetcode.com/problems/first-unique-character-in-a-string/

This solution efficiently identifies the first unique character in the given string. It utilizes an array to maintain the frequency of each character and then scans the string to find the first character with a frequency of 1, returning its index.

Related Post