First Unique Character
Easy strings · hashing
Description
Constraints
0 <= length <= 100000
Examples
Input: s = "loveleetcode"
Output: 2
Hints (1)
- Count each character, then scan for the first count of one.
Solutions
Count then scan. · Time O(n) · Space O(1)
func firstUniqChar(s string) int {
count := map[byte]int{}
for i := 0; i < len(s); i++ {
count[s[i]]++
}
for i := 0; i < len(s); i++ {
if count[s[i]] == 1 {
return i
}
}
return -1
}
Count then scan. · Time O(n) · Space O(1)
function firstUniqChar(s) {
const count = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
for (let i = 0; i < s.length; i++) if (count[s[i]] === 1) return i;
return -1;
}
Count then scan. · Time O(n) · Space O(1)
function firstUniqChar($s) {
$count = [];
for ($i = 0; $i < strlen($s); $i++) { $count[$s[$i]] = ($count[$s[$i]] ?? 0) + 1; }
for ($i = 0; $i < strlen($s); $i++) { if ($count[$s[$i]] === 1) { return $i; } }
return -1;
}
Count then scan. · Time O(n) · Space O(1)
def firstUniqChar(s):
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
for i, c in enumerate(s):
if count[c] == 1:
return i
return -1
Count then scan. · Time O(n) · Space O(1)
function firstUniqChar(s: string): number {
const count: Record<string, number> = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
for (let i = 0; i < s.length; i++) if (count[s[i]] === 1) return i;
return -1;
}
Create a free account to submit solutions, track progress and save problems.
Create account