class Solution:
def firstUniqChar(self, s: str) -> int:
from collections import Counter
count = Counter(s)
for idx, char in enumerate(s):
if count[char] == 1:
return idx
return -1
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
for (int i = 0; i < s.size(); ++i) {
if (count[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
};
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
var firstUniqChar = function(s) {
const count = {};
for (let char of s) {
count[char] = (count[char] || 0) + 1;
}
for (let i = 0; i < s.length; i++) {
if (count[s[i]] === 1) {
return i;
}
}
return -1;
};
Given a string s
, find the index of the first non-repeating character in it and return its index. If it does not exist, return -1
.
The string s
consists only of lowercase English letters. You must find the character that appears exactly once and is the earliest such character (i.e., has the smallest index). If no such character exists, return -1
.
Constraints:
s.length
≤ 105s
consists of only lowercase English letters.When approaching this problem, the first idea is to check each character in the string and see if it appears only once. The naive way would be to, for every character, scan the entire string and count its occurrences. However, this would result in a time-consuming solution, especially for long strings.
To optimize, we can realize that it's more efficient to count the frequency of each character in a single pass, and then, in a second pass, find the first character with a count of one. This avoids unnecessary repeated scans and leverages data structures for fast lookups.
The key shift is moving from a brute-force approach (checking every character against every other) to an optimized approach using counting (hash maps or arrays), which is much faster.
-1
.We use a hash map (or array) because it allows us to store and retrieve counts for each character in constant time. This makes both passes through the string efficient.
Input: s = "leetcode"
Result: The first unique character is 'l' at index 0.
Another example: s = "loveleetcode"
Result: The first unique character is 'v' at index 2.
Brute-force Approach:
Optimized Approach (Counting):
The optimized approach is much faster for large strings.
The "First Unique Character in a String" problem can be solved efficiently by counting character frequencies and then scanning for the first unique one. Using a hash map or array for counting allows us to check each character's count in constant time, resulting in a linear time solution. This approach is elegant because it separates counting and searching, making the code simple, fast, and easy to understand.