First Unique Character
EasyGiven a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Examples
| Input | Output |
|---|---|
| s = "leetcode" | 0 |
| s = "aabb" | -1 |
Python Solution
def first_uniq_char(s: str) -> int:
counts = {}
for c in s:
counts[c] = counts.get(c, 0) + 1
for i, c in enumerate(s):
if counts[c] == 1:
return i
return -1JavaScript Solution
function firstUniqChar(s) {
const counts = {};
for (const c of s) counts[c] = (counts[c] || 0) + 1;
for (let i = 0; i < s.length; i++) {
if (counts[s[i]] === 1) return i;
}
return -1;
}Step-by-Step Explanation
- First pass: count frequency of each character.
- Second pass: find the first character with count 1.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
StringHash Map
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix