Skip to main content

First Unique Character in a String

LeetCode 387 | Difficulty: Easy​

Easy

Problem Description​

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:

The character 'l' at index 0 is the first character that does not occur at any other index.

Example 2:

Input: s = "loveleetcode"

Output: 2

Example 3:

Input: s = "aabb"

Output: -1

Constraints:

- `1 <= s.length <= 10^5`

- `s` consists of only lowercase English letters.

Topics: Hash Table, String, Queue, Counting


Approach​

Hash Map​

Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?

When to use

Need fast lookups, counting frequencies, finding complements/pairs.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 148 ms)​

MetricValue
Runtime148 ms
MemoryN/A
Date2018-04-09
Solution
public class Solution {
public int FirstUniqChar(string s) {
Dictionary<char, int> occurences = new Dictionary<char, int>();
int m = s.Length;

for (int i = 0; i < m; i++)
{
if(!occurences.ContainsKey(s[i]))
{
occurences.Add(s[i], 1);
}
else
{
occurences[s[i]]++;
}
}
for (int i = 0; i < m; i++)
{
if(occurences[s[i]]==1) return i;
}
return -1;
}
}

Complexity Analysis​

ApproachTimeSpace
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Hash map gives O(1) lookup β€” think about what to use as key vs value.