Member-only story
In today’s blog, we’ll tackle the popular LeetCode problem 387. First Unique Character in a String. This problem is common in coding interviews and offers a chance to dive into concepts like hash maps, array manipulation, and even two-pointer techniques. In this post, we’ll explore multiple Java solutions with detailed explanations and complexity analysis.
🤔 Problem Statement
Level 🔥 Easy
Given a string s
, find the first non-repeating character and return its index. If no unique character exists, return -1
.
Examples:
- Input:
s = "leetcode"
Output:0
Explanation:'l'
is the first character that does not repeat. - Input:
s = "loveleetcode"
Output:2
Explanation:'v'
is the first character that does not repeat. - Input:
s = "aabb"
Output:-1
Explanation: There is no unique character.
💡 Solution
✍ Approach 1: Using HashMap
Use a HashMap to store the count of each character. After constructing the map, iterate through the string again to find the first character with a count of 1:
import java.util.HashMap;
public class Solution {
public int firstUniqChar(String…