Dare2Solve
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
. The problem asks for the position of the first character that appears exactly once in the string, considering its left-to-right order.
To determine the first unique character, we need to count the occurrences of each character in the string. If a character appears only once, it is a candidate for being the "first unique character." The challenge is to efficiently keep track of character counts and then identify the first one with a count of 1.
-1
.-1
if no such character exists.O(n), where n
is the length of the string. We perform two passes through the string: one for counting and one for identifying the first unique character.
O(1), because the hash map holds at most 26 key-value pairs (for lowercase English letters).
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> charCount;
// Count occurrences of each character
for (char c : s) {
charCount[c]++;
}
// Find the first character that occurs only once
for (int i = 0; i < s.size(); i++) {
if (charCount[s[i]] == 1) {
return i;
}
}
return -1;
}
};
class Solution:
def firstUniqChar(self, s: str) -> int:
char_count = {}
# Count occurrences of each character
for c in s:
if c not in char_count:
char_count[c] = 0
char_count[c] += 1
# Find the first character that occurs only once
for i in range(len(s)):
if char_count[s[i]] == 1:
return i
return -1
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> charCount = new HashMap<>();
// Count occurrences of each character
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// Find the first character that occurs only once
for (int i = 0; i < s.length(); i++) {
if (charCount.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
var firstUniqChar = function (s) {
s = s.split('')
let map = {}
for (let i of s) {
if (!map[i]) map[i] = 0
map[i] += 1
}
for (let i in s) {
if (map[s[i]] === 1) return i
}
return -1
};