First Unique Character in a String
Easy
Topics
Given a string s, return the index of the first non-repeating character. If none exists, return -1.
Example 1
repeatsfirst unique
The answer is the index of the first character that appears exactly once in the whole string — index 0 here. First means first by position, which is not the same as the first character you have not seen before.
Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "leetcode" Output: 0
Example 2
repeatsfirst unique
Input: s = "loveleetcode" Output: 2
Example 3
repeats
Every character in the string appears more than once, so there is no unique one and the answer is
-1.Input: s = "aabb" Output: -1
Constraints
- 1 <= s.length <= 10^5
- s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A character is the answer if it appears exactly once. Count every character first, then scan left to right for the first with a count of 1.
Approach
- Build a frequency map of all characters.
- Scan the string; return the index of the first character whose count is 1.
- If none, return -1.
Walkthrough
s = "loveleetcode"
counts: l:2 o:2 v:1 e:4 t:1 c:1 d:1
first count==1 while scanning -> index 2 (v)Complexity
- Time — O(n): two passes over the string.
- Space — O(1): the count map is bounded by the 26-letter alphabet.
Common Pitfalls
- Scan the string for the first count of 1, not the counter. A Counter preserves first-encounter order, which is not the same as position: on
bcbabcthe first unique character isaat index 3, but walking the counter findsaas its third key and reports 2. - Two passes is the point. One pass cannot know a character is unique until the whole string has been read.
Full Solution — all languages
class Solution:
def firstUniqChar(self, s):
from collections import Counter
cnt = Counter(s)
for i, c in enumerate(s):
if cnt[c] == 1:
return i
return -1import java.util.*;
class Solution {
public int firstUniqChar(String s) {
int[] cnt = new int[26];
for (int i = 0; i < s.length(); i++) cnt[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++) if (cnt[s.charAt(i) - 'a'] == 1) return i;
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int firstUniqChar(string s) {
int cnt[26] = {0};
for (char c : s) cnt[c - 'a']++;
for (int i = 0; i < (int)s.size(); i++) if (cnt[s[i] - 'a'] == 1) return i;
return -1;
}
};/**
* @param {string} s
* @return {number}
*/ var firstUniqChar = function(s) {
const cnt = {};
for (const c of s) cnt[c] = (cnt[c] || 0) + 1;
for (let i = 0; i < s.length; i++) if (cnt[s[i]] === 1) return i;
return -1;
};