First Unique Unicorn
๐ฆ First Unique Unicorn
Difficulty: Beginner Tags: strings, hash-map, counting Series: CS 102: Problem Solving & Logic
Problem
Find the first character in a string that appears only once, and return its index. If every character repeats, return -1.
Think of it like finding the first unique item in a list - the one that stands out because it appears exactly once!
Input
s = str # A string to search
Output
int # Index of first unique character, or -1 if none exist
Constraints
- String length โค 100,000
- String contains only lowercase English letters (a-z)
Examples
Example 1: Unique Character Found
Input: "leetcode"
Output: 0
Why? Let's count each character: - 'l' appears 1 time โ UNIQUE! - 'e' appears 3 times - 't' appears 1 time - 'c' appears 1 time - 'o' appears 1 time - 'd' appears 1 time
The first unique character is 'l' at index 0.
Example 2: No Unique Characters
Input: "aabb"
Output: -1
Why? Character counts: - 'a' appears 2 times - 'b' appears 2 times
Every character repeats, so there's no unique character. Return -1.
Example 3: Unique Character Later in String
Input: "loveleetcode"
Output: 2
Why? Character counts: - 'l' appears 2 times - 'o' appears 2 times - 'v' appears 1 time โ UNIQUE! - 'e' appears 4 times - 't' appears 1 time - 'c' appears 1 time - 'd' appears 1 time
The first unique character is 'v' at index 2 (even though 't', 'c', 'd' are also unique).