Find index of first unique character
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Find index of 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
- 1 <= len(s) <= 10^5 (an empty string returns -1)
- s consists of lowercase and uppercase English letters
- The check is case-sensitive: 'a' and 'A' are distinct
Examples
Input: ("leetcode",)
Expected Output: 0
Explanation: Every character in 'leetcode' except 'e','t','c','o','d'... actually 'l' at index 0 appears only once, so the answer is 0.
Input: ("loveleetcode",)
Expected Output: 2
Explanation: 'l','o','e' repeat; 'v' at index 2 is the first character that appears exactly once.
Input: ("aabb",)
Expected Output: -1
Explanation: Both 'a' and 'b' appear twice, so no character is unique; return -1.
Input: ("",)
Expected Output: -1
Explanation: An empty string has no characters, so return -1.
Input: ("z",)
Expected Output: 0
Explanation: A single character is trivially unique; its index 0 is returned.
Input: ("aA",)
Expected Output: 0
Explanation: Case-sensitive: 'a' and 'A' are different characters, each appearing once, so the first one at index 0 is returned.
Input: ("dddccdbba",)
Expected Output: 8
Explanation: 'd','c','b' all repeat; only the final 'a' at index 8 appears exactly once.
Input: ("abcabd",)
Expected Output: 2
Explanation: 'a' and 'b' repeat; 'c' at index 2 is the first character that appears exactly once.
Hints
- First count how many times each character occurs. A hash map (or a fixed-size array indexed by character) works well.
- After counting, scan the string left to right and return the index of the first character whose count is exactly 1.
- Two linear passes give O(n) time. For a fixed alphabet, the count storage is O(1) extra space.