KatInterview

Earliest Non-Repeating Character with Optional Case Folding

StringsAuto-graded · 23 test cases
EasyAuto-gradedStringsstringshash-mapcounting

Last updated

Find the position of the earliest character that occurs exactly once in a string, with a flag that switches between case-sensitive and case-insensitive matching.

Earliest Non-Repeating Character

You are given a string s and a boolean case_sensitive. Return the 0-based index in s of the leftmost character that occurs exactly once in the whole string. If no character occurs exactly once, return -1.

How characters are compared

  • If case_sensitive is True, two characters are the same only when they are identical. 'a' and 'A' are different.
  • If case_sensitive is False, two characters are the same when their case-folded forms are equal. Fold each character on its own with Python's str.casefold(). For English letters this is the same as lowercasing, so 'a' and 'A' are the same character.

The returned index always refers to the original string s, never to a modified copy.

Rules

  • A character is a candidate if, under the comparison above, it matches no other character in s.
  • If several characters qualify, return the smallest index.
  • The empty string has no such character, so return -1.
  • Digits, spaces and punctuation are treated like any other character.

Constraints

  • 0 <= len(s) <= 10^5
  • s consists of printable characters. Mostly English letters are expected, but any character may appear.
  • case_sensitive is a boolean.
  • The function returns an int.

Examples

Example 1

Input: earliest_nonrepeating_index('leetcode', True)

Output: 0

Example 2

Input: earliest_nonrepeating_index('loveleetcode', True)

Output: 2

Example 3

Input: earliest_nonrepeating_index('aabb', True)

Output: -1

Example 4

Input: earliest_nonrepeating_index('AaBbA', False)

Output: -1

Hints

Hint 1

To know whether a character is unique, you must have seen the whole string, so think about doing more than one pass.

Hint 2

Build a frequency table keyed by the comparison key: the character itself when case-sensitive, or its casefolded form otherwise.

Hint 3

After counting, walk the string from left to right and return the first index whose key has a count of exactly 1; return -1 if you finish the loop.