Find the Original Typed String I (LeetCode 3330): Solution and Explanation

Easy
String

Alice held one key too long at most once, so one block of equal letters may be stretched. Given the screen text, count how many different strings she could have meant.

Intuition

The screen text itself is always possible, because maybe nothing went wrong. That gives 1.

A held key only stretches one block of equal consecutive letters. A block of length L could have been meant as any length from 1 to L - 1, which adds L - 1 more originals.

Adding L - 1 over every block is the same as counting each position whose letter matches the letter just before it.

Approach: Count equal neighbors

  1. Start with ans = 1 for the text as typed.
  2. For each i from 1 to n - 1, if word[i] == word[i - 1], add 1 to ans.
  3. Return ans.

Step-by-step example

word = "abbcccc"
  1. Start with ans = 1 for "abbcccc" itself.
  2. Index 2: 'b' equals 'b', so the 'b' block could have been one 'b'. ans = 2.
  3. Indices 4, 5 and 6: each 'c' repeats the previous 'c', so the 'c' block could have been 1, 2 or 3 long. ans = 5.
  4. Return 5.

Code: Python, Java, C++

1class Solution:
2    def possibleStringCount(self, word: str) -> int:
3        ans = 1
4        for i in range(1, len(word)):
5            if word[i] == word[i - 1]:
6                ans += 1
7        return ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass compares each character with the one before it.

Space

O(1)

Only a counter and a loop index are kept.

Other approaches

Group into blocks (time O(n), space O(n))

Split the word into blocks of equal letters (for example with itertools.groupby) and return 1 plus the sum of len(block) - 1. Same result, slightly more code.

Generate every candidate (time O(n^2), space O(n^2))

Build each shortened string into a set and return its size. It works for n up to 100 but wastes time and memory building strings.

Common mistakes

  • Forgetting the +1 for the typed text itself. A word with no repeats still has one answer.
  • Multiplying choices across blocks. The long press happened at most once, so only one block can be shortened.
  • Counting a block of length L as L choices instead of L - 1 extra ones; the full length is already the typed text.

Frequently asked questions

Can different blocks give the same candidate string?

No. Shortening a different block, or the same block to a different length, always changes a different part of the string, so every candidate is distinct.

Why is the answer for "aaaa" equal to 4?

The single block of four 'a' could have been meant as 4, 3, 2 or 1 letters long.

What changes in the follow-up problem?

Find the Original Typed String II allows many held keys and a minimum length, which turns the count into a dynamic programming problem.