Expand a Compact Letter-and-Count String
StringsAuto-graded · 23 test casesLast updated
Parse a string of letters with optional multi-digit repeat counts, treating a missing count as one, and rebuild the expanded text in a single left-to-right pass.
Expand a Compact Letter-and-Count String
A text made of lowercase letters was shrunk into a compact form. In this form, every letter is optionally followed by a number saying how many times that letter should appear. If the number is left out, the letter appears exactly once. For instance, a5b3c expands to aaaaabbbc.
Write a function that takes the compact string and returns the fully expanded text.
Rules
- The input is a series of tokens. Each token is a single lowercase letter, optionally followed by a count.
- A count is a sequence of one or more decimal digits. It never begins with
0and its value is at least 1. Counts may span several digits, soa12means twelve copies ofa. - A token with no count produces one copy of its letter. A token with count
cproducesccopies. - Process the tokens from left to right and concatenate what they produce.
- Neighbouring tokens may share the same letter. Each token is expanded independently, with no merging.
- The input is always valid under these rules.
Constraints
1 <= len(s) <= 10^4sconsists only of lowercase English letters and the digits0-9, and its first character is a letter.- Every count satisfies
1 <= count <= 10^5. - The expanded string has length at most
10^5.
Examples
Example 1
Input: expand_compact_string('a5b3c')
Output: 'aaaaabbbc'
Example 2
Input: expand_compact_string('q10e')
Output: 'qqqqqqqqqqe'
Example 3
Input: expand_compact_string('ab2a')
Output: 'abba'
Hints
Hint 1
Every token starts with a letter, so whenever you stand on a letter you know a new token begins there.
Hint 2
After reading a letter, keep moving a second index forward while the characters are digits. The whole slice of digits is the count, not just one digit.
Hint 3
If no digits followed the letter, use a count of 1. Collect the pieces in a list and join them once at the end instead of concatenating repeatedly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the string once from left to right with two indices.
- At index
ithere is always a letter, because the string starts with a letter and each token ends right before the next letter. - Move a second index
jforward over all digits that follow that letter. The slices[i+1:j]is the full count for this token. - If no digits were found, the count is 1. Otherwise convert the digit slice to an integer, which naturally handles multi-digit counts such as
12or100000. - Append
letter * countto a list, seti = j, and continue with the next token. - After the loop, join the list into the final string.
A common mistake is to read only a single digit as the count, which breaks inputs like q10e. The count is the entire maximal run of digits after a letter.
Why it is correct
Each token has the form letter digit*, and every letter begins a new token. So token boundaries are unambiguous: a token's digits extend from just after its letter up to the next letter or the end of the string. The inner loop consumes exactly that maximal run of digits, so each outer iteration consumes exactly one token.
Invariant: at the start of each outer iteration, the prefix s[:i] has been split into complete tokens and the list holds their expansions in order. Each iteration extends this by one token, so when i reaches n the joined list is the concatenation of every token's expansion.
Adjacent tokens with the same letter, such as a2a3, need no special care since each is expanded on its own, giving aaaaa. An explicit count of 1 means the same as no count, which the code handles the same way.
Complexity
Let n = len(s) and m be the length of the output.
- Time: O(n + m). Each input character is visited once, building each repeated chunk costs its length (summing to
m), and the final join is O(m). - Space: O(m) for the pieces and the result.
Reference solution
def expand_compact_string(s: str) -> str:
parts = []
i = 0
n = len(s)
while i < n:
ch = s[i]
i += 1
j = i
while j < n and s[j].isdigit():
j += 1
count = int(s[i:j]) if j > i else 1
parts.append(ch * count)
i = j
return ''.join(parts)