Earliest Non-Repeating Character with Optional Case Folding
StringsAuto-graded · 23 test casesLast 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_sensitiveisTrue, two characters are the same only when they are identical.'a'and'A'are different. - If
case_sensitiveisFalse, two characters are the same when their case-folded forms are equal. Fold each character on its own with Python'sstr.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^5sconsists of printable characters. Mostly English letters are expected, but any character may appear.case_sensitiveis 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Whether a character is unique depends on the entire string, but which unique character comes first depends on position. So the solution uses two passes.
- Counting pass. Compute a comparison key for every character: the character itself if
case_sensitiveis true, otherwisech.casefold(). Store the key for each position in a list and increment a counter in a dictionary for that key. - Scan pass. Go through the stored keys in order and return the first index whose key has a count of exactly 1. If the loop ends without a match, return
-1.
Why it is correct
- Every character adds exactly one to exactly one key's counter, so after the first pass
counts[k]is the number of positions whose key isk. - Position
iholds a non-repeating character exactly whencounts[keys[i]] == 1. - The second pass checks indices in increasing order, so the first match is the smallest qualifying index.
- If nothing matches, including for the empty string, the function returns
-1. - The flag changes only how keys are built, so one code path handles both modes.
Complexity
- Time: O(n), since there are two linear passes and dictionary operations are O(1) on average.
- Space: O(n) for the stored keys, plus at most one dictionary entry per distinct key. The key list can be dropped by recomputing keys in the second pass, which leaves only the dictionary (O(1) for a fixed alphabet).
Reference solution
def earliest_nonrepeating_index(s, case_sensitive):
counts = {}
keys = []
for ch in s:
key = ch if case_sensitive else ch.casefold()
keys.append(key)
counts[key] = counts.get(key, 0) + 1
for i, key in enumerate(keys):
if counts[key] == 1:
return i
return -1