Compact RLE Coder: Decode a String and Re-encode Under Pattern Limit
Dynamic ProgrammingAuto-graded · 20 test casesLast updated
Tests string parsing for RLE decoding and interval DP to find the shortest valid re-encoding when patterns are capped at length K.
Background
A compressed string is built from a sequence of tokens joined end-to-end. Each token looks like:
<count><pattern>
count— a positive integer in base 10 (one or more digits, no leading+).pattern— a non-empty string of lowercase lettersa–z.
Because digits never appear in patterns and letters never appear in counts, token boundaries are always unambiguous. The token expands to pattern repeated count times.
Example: "2aab3ab" expands as "aab"+"aab"+"ab"+"ab"+"ab" → "aabaabababab".
Your Tasks
Part A — Decode
Given a valid encoded string encoded, return its fully expanded form.
Part B — Optimal Re-encode
Given a plain string s and a positive integer K, produce an encoded string that:
- Decodes back to exactly
s. - Uses only patterns whose length is at most K in every token.
- Has the shortest possible total character count among all such encodings.
If several shortest encodings exist, return any one of them.
Return Value
Return a list of two strings: [decoded_result, encoded_result].
Notes
- Every token must follow the
<count><pattern>format; bare (uncounted) literal substrings are not allowed. - A single character, or any substring, can always be emitted as count
1, so a valid encoding always exists. countmay be 10 or larger; your decoder must handle multi-digit counts correctly.- For encoding, greedily taking the longest repeating run is not always optimal — the non-linear cost of extra digits in large counts means you must consider every valid count, not just the maximum.
Constraints
1 ≤ len(encoded) ≤ 1000andencodedis a valid token sequence.1 ≤ len(s) ≤ 200.1 ≤ K ≤ len(s).sand all patterns inencodedcontain only lowercase lettersa–z.- The decoded expansion of
encodedfits in memory as a plain Python string.
Examples
Example 1
Input: rle_decode_and_encode('2aab3ab', 'aabaabababab', 3)
Output: ['aabaabababab', '2aab3ab']
Example 2
Input: rle_decode_and_encode('1a', 'a', 1)
Output: ['a', '1a']
Hints
Hint 1
For decoding, scan left to right: collect consecutive digit characters to form the count, then collect consecutive letter characters to form the pattern. Repeat until the string is exhausted — digit/letter alternation makes boundaries unambiguous.
Hint 2
For encoding, think of it as a shortest-path problem over positions in s. Define dp[i] as the minimum encoded length of s[i:]. At each position, try every pattern length p from 1 to K and every valid repeat count c (all counts where s[i:i+c*p] is exactly c copies of s[i:i+p]), then pick the combination that minimises len(str(c)) + p + dp[i+c*p].
Hint 3
Watch out for the digit-cost cliff: going from count 9 to 10 adds a character to the count field, so taking the maximum run is not always cheapest. You must evaluate every count from 1 up to the maximum, not just the largest one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part A — Decoding
The token format makes boundaries self-evident: digits belong to the count field and letters belong to the pattern field, and they never overlap. A single left-to-right scan is enough.
At each step, advance past all consecutive digit characters and parse them as the integer count, then advance past all consecutive letter characters to read pattern. Append pattern * count to the result and repeat until the string is exhausted.
This runs in O(|encoded| + |output|) time and O(|output|) space — both dominated by writing the expanded string.
Part B — Optimal Re-encoding
Why greedy fails. You might think "always take the longest repeating run of the best pattern." The problem is that the digit cost of count is non-linear: going from count 9 to count 10 costs one extra character. So taking more repetitions can sometimes make the token longer, and greedily committing to the maximum run of one pattern can also block a better pattern that starts partway through.
DP formulation. Define dp[i] as the minimum number of encoded characters required to represent s[i:]. The base case is dp[n] = 0.
For each position i from right to left, every valid encoding of s[i:] starts with one token. A token is determined by choosing:
- a pattern length
pin[1, min(K, n-i)], - a repeat count
cin[1, max_repeats(i, p)], wheremax_repeatsis the largestcsuch thats[i:i+c*p]is exactlyccopies ofs[i:i+p].
The token covers s[i : i + c*p] and costs len(str(c)) + p characters. The recurrence is:
dp[i] = min over valid (p, c) of:
len(str(c)) + p + dp[i + c*p]
Because we evaluate every count from 1 up to the maximum (not just the maximum), the non-linear digit cost is handled correctly.
Reconstruction. While filling the table, store the (c, pattern, next_position) triple that achieved the minimum at each i. After computing dp[0], follow these choices from left to right to build the encoded string.
Why it is correct. Any valid encoding decomposes into a first token followed by a valid encoding of the remaining suffix. The DP explores every possible first token exhaustively, and optimal substructure guarantees that combining the best first token with the best suffix encoding yields the global optimum.
Complexity
| Time | Space | |
|---|---|---|
| Decode | O(|encoded| + |output|) | O(|output|) |
| Encode (DP) | O(n² · K) worst case* | O(n + K) |
*The inner loop runs at most (n-i)/p iterations for a given p, summed over p = 1..K and i = 0..n-1 this is O(n² · H_K). On inputs with short runs (typical text), it is much faster in practice.
Edge Cases
- K = 1: only single-character patterns are allowed, giving classic character-level RLE.
"aaab"becomes"3a1b". - Single character:
s = "z"must encode as"1z"— the count field is mandatory. - Multi-digit counts:
"10a"decodes to tenas. The decoder must collect all consecutive digits, not just one. - Count of 10 boundary:
"a" * 10costs 3 characters as"10a"but 4 as"9a1a", so the DP correctly prefers"10a". - K ≥ n: the whole string fits in one token
"1<s>"at costn+1, but shorter encodings may exist and the DP finds them.
Reference Solution
from typing import List
def rle_decode_and_encode(encoded: str, s: str, K: int) -> List[str]:
# ── Part A: decode ────────────────────────────────────────────────────────
decoded_parts = []
i = 0
while i < len(encoded):
# Collect the digit run → count
j = i
while j < len(encoded) and encoded[j].isdigit():
j += 1
count = int(encoded[i:j])
# Collect the letter run → pattern
end = j
while end < len(encoded) and encoded[end].isalpha():
end += 1
decoded_parts.append(encoded[j:end] * count)
i = end
# ── Part B: optimal encode with pattern length ≤ K ───────────────────────
n = len(s)
INF = float('inf')
# dp[i] = minimum number of encoded characters needed for s[i:]
dp = [INF] * (n + 1)
dp[n] = 0
# choice[i] = (count, pattern, next_position) that achieves dp[i]
choice = [None] * n
for i in range(n - 1, -1, -1):
best = INF
best_token = None
# Try every pattern length p from 1 up to K (and at most n-i)
for p in range(1, min(K, n - i) + 1):
pattern = s[i : i + p]
c = 0
pos = i
# Extend the run of `pattern` as far as possible, evaluating
# each count along the way (not just the maximum).
while pos + p <= n and s[pos : pos + p] == pattern:
c += 1
token_chars = len(str(c)) + p # digits in count + pattern length
candidate = token_chars + dp[pos + p]
if candidate < best:
best = candidate
best_token = (c, pattern, pos + p)
pos += p
dp[i] = best
choice[i] = best_token
# Reconstruct the encoded string by following the stored choices
parts = []
i = 0
while i < n:
c, pattern, i = choice[i]
parts.append(str(c) + pattern)
return [''.join(decoded_parts), ''.join(parts)]