Shrink Repeated Letters into Letter-Count Pairs
StringsAuto-graded · 24 test casesLast updated
Encode each maximal run of equal letters as the letter plus its decimal count, and fall back to the input when the encoding is not strictly shorter.
Run-Length Shrinker
You are given a string text. Produce a shorter encoding of it by describing each stretch of repeated letters with the letter followed by how many times it repeats. If the encoding does not end up strictly shorter than the input, give back the input unchanged.
Encoding rules
- A run is a maximal block of adjacent, identical characters. It cannot be extended on either side by another copy of the same character.
- Replace every run with the run's character followed by the run's length written in ordinary decimal digits. For instance,
aabcccccaaabecomesa2b1c5a3. - Every run is encoded, even those of length 1: a lone
bbecomesb1. - Comparison is case-sensitive.
aandAare different characters, soaAcontains two runs. - A run longer than 9 uses all of its digits. Twelve consecutive
acharacters are writtena12. - Decide what to return only after the entire string has been encoded: return the encoded string if its length is strictly less than
len(text). If it is equal or longer, returntextitself. - An empty input returns an empty string.
Task
Implement shrink_runs(text) that returns the encoded string or the original, according to the rules above.
Constraints
0 <= len(text) <= 10^5textconsists only of English letters (a-zandA-Z).
Examples
Example 1
Input: shrink_runs('aabcccccaaa')
Output: 'a2b1c5a3'
Example 2
Input: shrink_runs('aabb')
Output: 'aabb'
Example 3
Input: shrink_runs('aaaaaaaaaaB')
Output: 'a10B1'
Hints
Hint 1
Think of the string as a sequence of maximal blocks. For each block you only need its character and its length.
Hint 2
Use two indices: one at the start of the current block and one that moves forward while the character stays the same. When it stops, the block length is the difference, and the next block starts there.
Hint 3
Collect the pieces in a list and join once at the end. Convert the count with str() so counts of 10 or more keep all digits. Compare lengths at the end with a strict less-than.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the string once, treating it as a series of maximal runs. Keep a start index i for the current run and advance a second index j while text[j] == text[i]. When j stops, the run is text[i:j] with length j - i. Append the character and the decimal form of the length to a list, then set i = j to begin the next run. After the scan, join the list into one string and return it only if its length is strictly smaller than the input length; otherwise return the input.
The list-and-join approach matters: repeatedly concatenating onto a string can become quadratic, while a single join is linear.
Why it is correct
- Runs partition the string. The inner loop stops at the first differing character or at the end, so each block is maximal. Moving
itojstarts the next block exactly where the previous one ended, with no gaps or overlaps. The final run is handled inside the same loop, so no special flush is needed. - Encoding follows the rules. Runs of length 1 produce
x1, andstr()writes all digits of long counts such as12or100000. - Case sensitivity comes for free, since
'a' != 'A'. - The length check happens last, on the fully encoded string, and uses a strict
<, so ties return the original text. - The empty string is returned immediately.
Complexity
- Time: O(n). Each character is visited once by
j, and converting counts to strings costs at most the total number of digits, which is bounded by O(n). - Space: O(n) for the list of pieces and the encoded string.
Reference solution
def shrink_runs(text: str) -> str:
if not text:
return text
parts = []
n = len(text)
i = 0
while i < n:
j = i
while j < n and text[j] == text[i]:
j += 1
parts.append(text[i])
parts.append(str(j - i))
i = j
encoded = "".join(parts)
return encoded if len(encoded) < n else text