KatInterview

Shrink Repeated Letters into Letter-Count Pairs

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringsstringstwo-pointersrun-length-encoding

Last 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, aabcccccaaa becomes a2b1c5a3.
  • Every run is encoded, even those of length 1: a lone b becomes b1.
  • Comparison is case-sensitive. a and A are different characters, so aA contains two runs.
  • A run longer than 9 uses all of its digits. Twelve consecutive a characters are written a12.
  • 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, return text itself.
  • 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^5
  • text consists only of English letters (a-z and A-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.