KatInterview

Find the First Character Appearing Exactly Once

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarrays & hashinghash countingstrings

Last updated

Tests the ability to use hash counting (frequency maps) to efficiently locate the first character in a string that appears exactly once.

First Unique Character in a Stream

You are given a string message representing a sequence of lowercase English letters received one by one (left to right). Your task is to find the index of the first character that appears exactly once in the entire string.

If no such character exists, return -1.

Important: You must consider the full string when determining character frequencies — a character is "unique" only if its total count across the entire string is exactly 1. Then, among all such unique characters, return the index of the one that appears earliest (leftmost) in the string.

Constraints

  • 0 <= len(message) <= 2000
  • message consists only of lowercase English letters ('a'–'z').
  • If message is empty, return -1.
  • If multiple characters each appear exactly once, return the smallest index among them.
  • If no character appears exactly once, return -1.

Examples

Example 1

Input: first_unique_char_index('interview')

Output: 1

Example 2

Input: first_unique_char_index('aabbcc')

Output: -1

Example 3

Input: first_unique_char_index('abacabad')

Output: 3

Hints

Hint 1

Count the frequency of every character in the string using a dictionary or array of size 26 before scanning for the answer.

Hint 2

Once you have the frequency map, do a second pass from left to right and return the index of the first character whose count equals 1.

Hint 3

Think about what happens when all characters repeat — make sure your code returns -1 in that case rather than an invalid index.