KatInterview

Earliest Non-Repeating Symbol Position

StringsAuto-graded · 23 test cases
EasyAuto-gradedStringshash-mapcountingstring

Last updated

Locate the index of the earliest symbol in an alphanumeric string that occurs only once, using frequency counting and an ordered scan, or return -1.

You are given a string text made up of uppercase letters, lowercase letters, and digits.

Find the symbol that appears exactly one time in the entire string and sits at the lowest index among all such symbols. Return that index (zero-based). If every symbol in the string occurs more than once, or the string is empty, return -1.

Rules to follow precisely:

  • Matching is case-sensitive: 'a' and 'A' are two different symbols.
  • Digits are treated like any other symbol.
  • "Earliest" refers to position in the original string, not alphabetical order.
  • Return the index, not the symbol itself.

Your solution should run in linear time in the length of the string.

Constraints

  • text contains only characters from a-z, A-Z, and 0-9.
  • 0 <= len(text) <= 10^5
  • The function returns an integer: a valid index in text, or -1.

Examples

Example 1

Input: earliest_single_occurrence('leetcode')

Output: 0

Example 2

Input: earliest_single_occurrence('loveleetcode')

Output: 2

Example 3

Input: earliest_single_occurrence('aA1bB2a')

Output: 1

Hints

Hint 1

Whether a symbol is unique depends on the whole string, so looking at it once from left to right is not enough on its own.

Hint 2

First tally how many times every symbol occurs. Then walk through the string again in its original order and check each symbol's tally.

Hint 3

Iterate over the string itself in the second pass (not over the tally table) so the first match is guaranteed to be the one with the smallest index.