LeetCode 387: First Unique Character in a String – Java HashMap Solution Explained

Learn how to solve LeetCode 387 First Unique Character in a String using HashMap in Java. Includes brute force approach, optimized solution, intuition, dry run, complexity analysis, interview explanation, and common mistakes.

Krishna Shrivastava
1 views
LinkedInGithubX
0
0
LeetCode 387: First Unique Character in a String – Java HashMap Solution Explained
Listen to articleAudio version
Ad
Advertisement

Introduction

LeetCode 387 – First Unique Character in a String is one of the most common beginner-friendly string and hashing interview problems.

This problem helps developers understand:

  1. Frequency counting
  2. HashMap usage
  3. String traversal
  4. Character manipulation
  5. Efficient lookup techniques

It is frequently asked in coding interviews because it tests both:

  1. Logical thinking
  2. Time complexity optimization

Problem Link

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

Problem Statement

Given a string:

s

Return:

Index of the first non-repeating character

If no unique character exists:

Return -1

Example 1

Input

s = "leetcode"

Output

0

Explanation:

'l'

appears only once and is the first unique character.

Example 2

Input

s = "loveleetcode"

Output

2

Explanation:

'v'

is the first character that appears only once.

Example 3

Input

s = "aabb"

Output

-1

All characters repeat.

Intuition

To identify the first unique character:

We first need to know:

How many times every character appears

A HashMap is perfect for frequency counting.

After counting:

We traverse the string again and return the first character whose frequency is:

1

Brute Force Approach

Idea

For every character:

  1. Traverse the entire string
  2. Count occurrences
  3. Return the first character with count = 1

Brute Force Complexity

Time Complexity

O(N²)

because nested traversal is required.

Space Complexity

O(1)

Optimized HashMap Approach

Idea

Use a HashMap to store:

character → frequency

Then scan the string again.

The first character with frequency:

1

is the answer.

Java Solution

class Solution {

public int firstUniqChar(String s) {

HashMap<Character, Integer> mp = new HashMap<>();

for(int i = 0; i < s.length(); i++) {
mp.put(s.charAt(i), mp.getOrDefault(s.charAt(i), 0) + 1);
}

for(int i = 0; i < s.length(); i++) {

if(mp.get(s.charAt(i)) == 1) {
return i;
}
}

return -1;
}
}

Cleaner Optimized Version

class Solution {

public int firstUniqChar(String s) {

int[] freq = new int[26];

for(char ch : s.toCharArray()) {
freq[ch - 'a']++;
}

for(int i = 0; i < s.length(); i++) {

if(freq[s.charAt(i) - 'a'] == 1) {
return i;
}
}

return -1;
}
}

Why This Works

The algorithm works in two passes.

First Pass

Store frequency of every character.

Example:

"leetcode"

Frequency map:

l → 1
e → 3
t → 1
c → 1
o → 1
d → 1

Second Pass

Traverse string from left to right.

The first character whose frequency equals:

1

is returned.

Dry Run

Input

s = "loveleetcode"

Step 1: Frequency Counting

l → 2
o → 2
v → 1
e → 4
t → 1
c → 1
d → 1

Step 2: Traverse Again

Index 0:

'l' → frequency 2

Index 1:

'o' → frequency 2

Index 2:

'v' → frequency 1

Return:

2

Time Complexity Analysis

Optimized HashMap Solution

Time Complexity

O(N)

because string traversal happens twice.

Space Complexity

O(1)

Only lowercase English letters exist.

Maximum storage remains fixed.

Brute Force vs Optimized

ApproachTime ComplexitySpace Complexity
Brute ForceO(N²)O(1)
HashMap / Frequency ArrayO(N)O(1)

Interview Explanation

In interviews, explain:

We use a frequency map to count occurrences of every character. Then we scan the string again to locate the first character whose frequency is exactly one.

This demonstrates:

  1. Hashing knowledge
  2. Frequency counting
  3. Efficient lookup usage
  4. Optimization skills

Common Mistakes

1. Returning Character Instead of Index

The problem asks for:

index

not the character itself.

2. Using Nested Loops

Nested traversal increases complexity unnecessarily.

3. Forgetting Second Traversal

HashMap only stores frequencies.

You still need:

left-to-right traversal

to find the first unique character.

FAQs

Q1. Why use HashMap?

Because frequency lookup becomes very efficient.

Q2. Can we use arrays instead?

Yes.

Since only lowercase letters exist:

int[26]

works perfectly.

Q3. Why traverse the string twice?

First pass counts frequency.

Second pass preserves original order.

Q4. Is this problem important for interviews?

Yes.

It is one of the most common hashing interview questions.

Related Problems

Practice these next:

  1. Valid Anagram
  2. Ransom Note
  3. Count the Number of Special Characters

Conclusion

LeetCode 387 is an excellent beginner-level problem for learning:

  1. Frequency counting
  2. HashMap usage
  3. String traversal
  4. Efficient lookup techniques

The key insight is:

Count character frequencies first, then find the first character with frequency equal to one.

This pattern is widely used in many real interview problems involving strings and hashing.

Ai Assistant Kas