Member-only story

🧑‍💻 LeetCode 387 — First Unique Character 🔥

Leo N
3 min readNov 12, 2024

--

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:

  1. Input: s = "leetcode"
    Output: 0
    Explanation: 'l' is the first character that does not repeat.
  2. Input: s = "loveleetcode"
    Output: 2
    Explanation: 'v' is the first character that does not repeat.
  3. 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…

--

--

Leo N
Leo N

Written by Leo N

🇻🇳 🇸🇬 🇲🇾 🇦🇺 🇹🇭 Engineer @ GXS Bank, Singapore | MSc 🎓 | Technical Writer . https://github.com/nphausg

No responses yet