First Unique Character in a String
LeetCode 387 | Difficulty: Easyβ
EasyProblem 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?
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.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 148 ms)β
| Metric | Value |
|---|---|
| Runtime | 148 ms |
| Memory | N/A |
| Date | 2018-04-09 |
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β
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.