Find index of first unique character
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Given a string s, return the index of the first character that appears exactly once; if none exists, return -1. Assume s may include both lowercase and uppercase English letters. Clarify whether the check is case-sensitive and implement both case-sensitive and case-insensitive variants. Follow-ups:
(
1) Optimize for a small fixed alphabet—can you use constant extra space?
(
2) How would you support full Unicode, including grapheme clusters and normalization issues?
(
3) If s arrives as a stream too large for memory, how would you detect the first unique character online? Analyze time and space complexity.
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.
Given a string `s`, return the index of the first character that appears exactly once in `s`. If no such character exists, return `-1`.
The string may include both lowercase and uppercase English letters. For this challenge the check is **case-sensitive**, so `'a'` and `'A'` are treated as different characters.
**Examples:**
- `s = "leetcode"` -> `0` (the first `'l'` is the first character that appears exactly once)
- `s = "loveleetcode"` -> `2` (the `'v'` at index 2 is the first unique character)
- `s = "aabb"` -> `-1` (no character appears exactly once)
**Follow-ups to discuss (no code required):**
1. For a small fixed alphabet (e.g. 52 ASCII letters), can you achieve O(1) extra space?
2. How would you extend this to full Unicode, accounting for grapheme clusters and normalization (NFC/NFD)?
3. If `s` arrives as a stream too large to fit in memory, how would you detect the first unique character online?
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.
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.