Coding problem · Easy · Basics
First Unique Character
Easy Algorithms & data structures
Given a string s of lower-case letters, return the index of the first character that appears exactly once. If there's none, return -1.
Example 1
Input: s = "leetcode" Output: 0
Example 2
Input: s = "loveleetcode" Output: 2
Example 3
Input: s = "aabb" Output: -1
Hints
Hint 1
First count how many times each character appears.
Hint 2
Then scan again and return the first index whose character has count 1.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Two passes: build a frequency map, then find the first character with frequency 1. Both passes are O(n).
Reference solution
function firstUniqueChar(s) {
const count = new Map();
for (const ch of s) count.set(ch, (count.get(ch) ?? 0) + 1);
for (let i = 0; i < s.length; i++) if (count.get(s[i]) === 1) return i;
return -1;
}
function firstUniqueChar(s: string): number {
const count = new Map<string, number>();
for (const ch of s) count.set(ch, (count.get(ch) ?? 0) + 1);
for (let i = 0; i < s.length; i++) if (count.get(s[i]) === 1) return i;
return -1;
}
from collections import Counter
def first_unique_char(s: str) -> int:
count = Counter(s)
for i, ch in enumerate(s):
if count[ch] == 1:
return i
return -1
<?php
function firstUniqueChar(string $s): int
{
$count = count_chars($s, 1);
for ($i = 0; $i < strlen($s); $i++) {
if ($count[ord($s[$i])] === 1) {
return $i;
}
}
return -1;
}
class Solution {
public int firstUniqueChar(String s) {
int[] count = new int[26];
for (char ch : s.toCharArray()) count[ch - 'a']++;
for (int i = 0; i < s.length(); i++) if (count[s.charAt(i) - 'a'] == 1) return i;
return -1;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy