Learnitweb

LeetCode 387: First Unique Character in a String

Problem Statement

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: 'l' is the first non-repeating character.

Example 2:

Input: s = "loveleetcode"
Output: 2
Explanation: 'v' is the first non-repeating character.

Constraints:

  • s consists of only lowercase English letters.

Approach (HashMap for General Characters)

  1. Count frequency using HashMap:
    • Loop through the string s.
    • For each character, store/update its count in a HashMap<Character, Integer>.
  2. Find first unique character:
    • Loop through s again.
    • For each character, check its count in the HashMap.
    • Return the index of the first character with count 1.
  3. Return -1 if none found:
    • If no character has count 1, return -1.

Advantages:

  • Works for any character, including uppercase letters, digits, or Unicode symbols.
  • Simple and readable.

Java Code Solution (HashMap)

import java.util.HashMap;
import java.util.Map;

public class FirstUniqueCharacterGeneral {

    public static int firstUniqChar(String s) {
        Map<Character, Integer> freqMap = new HashMap<>();

        // Step 1: Count frequency of each character
        for (char c : s.toCharArray()) {
            freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
        }

        // Step 2: Find the first unique character
        for (int i = 0; i < s.length(); i++) {
            if (freqMap.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1; // No unique character found
    }

    public static void main(String[] args) {
        String s = "aabb©xyz©";
        int result = firstUniqChar(s);
        System.out.println("Index of first unique character: " + result); // Output: 4 ('x')
    }
}

Dry Run Example

Input:

s = "aabb©xyz©"

Step-by-step Execution:

  1. Count frequency in HashMap:
a -> 2
b -> 2
© -> 2
x -> 1
y -> 1
z -> 1
  1. Iterate over string to find first unique:
IndexCharCountIs Unique?
0a2No
1a2No
2b2No
3b2No
4©2No
5x1Yes
  1. Return 5 as the first unique character index.

Textual Diagram for Understanding

s = "aabb©xyz©"
HashMap frequency:
a:2, b:2, ©:2, x:1, y:1, z:1

Check string order:
0: a -> 2 -> skip
1: a -> 2 -> skip
2: b -> 2 -> skip
3: b -> 2 -> skip
4: © -> 2 -> skip
5: x -> 1 -> first unique -> return 5

Complexity Analysis

  • Time Complexity: O(n)
    • n = length of string.
    • Two passes over the string: one for counting, one for checking.
  • Space Complexity: O(n)
    • HashMap stores count for all unique characters in s.