First Non-Repeating Character in a String
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to work with hash maps and character frequency counting in string processing. It tests practical coding proficiency, including efficient linear scanning and index tracking, and is commonly used to assess fundamental data structure skills in coding interviews.
Constraints
- 1 <= s.length <= 10^5
- s consists of lowercase English letters only ('a'-'z').
- "Non-repeating" means the character occurs exactly once in the entire string.
- Return the index of the FIRST such character; return -1 if none exists.
Examples
Input: ("leetcode",)
Expected Output: 0
Explanation: 'l' appears once and is the earliest such character, at index 0.
Input: ("loveleetcode",)
Expected Output: 2
Explanation: 'l' and 'o' both repeat; 'v' at index 2 is the first character appearing exactly once.
Input: ("aabb",)
Expected Output: -1
Explanation: Every character ('a','b') appears twice, so there is no non-repeating character.
Input: ("z",)
Expected Output: 0
Explanation: Single-character string: 'z' appears once, so index 0 is returned.
Input: ("aabbccddx",)
Expected Output: 8
Explanation: All of a,b,c,d repeat; 'x' is the only unique character, located at the last index 8.
Input: ("cc",)
Expected Output: -1
Explanation: 'c' appears twice, so no character is non-repeating.
Hints
- You need to know a character's total count across the whole string before you can decide it is unique, so a single left-to-right pass that decides on the spot is not enough — count first, then scan.
- Build a frequency map of every character in one pass (a fixed-size array of 26 works since input is lowercase letters).
- Do a second pass over the string in order and return the index of the first character whose count is exactly 1. If the loop finishes, return -1.