Find first unique character
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Find first unique character evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(s) <= 10^5
- s consists of alphanumeric characters (comparison is case-sensitive).
- Return -1 when no character appears exactly once (including the empty string).
Examples
Input: ("leetcode",)
Expected Output: 0
Explanation: 'l' is the first character that appears exactly once, at index 0.
Input: ("loveleetcode",)
Expected Output: 2
Explanation: 'l','o','e' all repeat; 'v' at index 2 is the first character appearing exactly once.
Input: ("aabb",)
Expected Output: -1
Explanation: Every character repeats, so no unique character exists.
Input: ("",)
Expected Output: -1
Explanation: Empty string edge case: there is no character to return.
Input: ("z",)
Expected Output: 0
Explanation: Single-character string: that character is trivially unique at index 0.
Input: ("aA",)
Expected Output: 0
Explanation: Case-sensitive: 'a' and 'A' are different characters, so 'a' at index 0 is unique.
Input: ("aabbc",)
Expected Output: 4
Explanation: Last-character-unique case: only 'c' appears once, at index 4.
Input: ("abcabd",)
Expected Output: 2
Explanation: 'a' and 'b' repeat; 'c' at index 2 is the first character that appears exactly once.
Hints
- First pass: count how many times each character appears using a hash map.
- Second pass: walk the string in order and return the index of the first character whose count is 1.
- Scanning the original string (not the map) on the second pass is what preserves the 'first' / original-order requirement.
- A sorting-based approach groups equal characters but loses original order unless it also stores indices, and costs O(n log n) versus O(n) here.