Problem Description
Alice is typing a target string but might accidentally press a key too long. When this happens, a letter is output multiple times instead of the intended number. However, such an error occurs on at most one key press throughout the entire string. Given the final displayed string word, determine how many possible original strings Alice might have intended to type.
Key Insights
- The final string can be divided into groups of consecutive identical characters.
- For any group with a single character, no error could have occurred.
- If a group has length L ≥ 2, then an error may have occurred in that group. Specifically, if that group is the one with the error, the intended number of characters could be any value between 1 and L-1.
- Since at most one error occurred, if an error happens in a group the other groups must be exactly as displayed.
- Additionally, it’s possible that no error occurred in any group, in which case the intended string is exactly the final string.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the word (we scan the string once).
Space Complexity: O(1) (using only a few counters and variables).
Solution
We solve the problem by iterating through the string and grouping consecutive identical characters. For each group:
- If its length is 1, there is only one possibility (no error).
- If its length is L (L ≥ 2), then if that group was the error group, the intended count could be any integer from 1 to L-1 (L-1 possibilities), otherwise the group remains as is.
Since the error occurs in at most one group, we can choose one group to “fix” (if eligible) while leaving all others unchanged. Thus, the total possibilities equals: 1 (case when no error occurred in any group) plus the sum of (L-1) for every group with length ≥2.
The algorithm uses a single pass (or a pass over groups) and constant extra space.