The Code Expander
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Citadel
Problem
Given an RLE-encoded string where each run is a decimal count followed by a character, return the decoded string. Counts can be multi-digit.
Compressed messages need a decoder to come alive.
Example 1
Input:
encoded = "3a2b4c"
Output:
"aaabbcccc"
Example 2
Input:
encoded = "1a1b1c"
Output:
"abc"
Worked solution and explanation
Why this problem exists in real interviews
This tests string parsing with state tracking: reading digits and characters in sequence to reconstruct the original data. It probes whether a candidate can handle multi-digit numbers and cleanly separate the parsing of counts from characters.
Break down the requirements
Step 1: Scan the string character by character
Accumulate digit characters into a number buffer. When you hit a non-digit, that is the character to repeat.
Step 2: Handle multi-digit counts
Numbers like 12a mean 12 repetitions. You must collect all consecutive digits before treating the next character as the letter.
Step 3: Append the repeated character to the result
Convert the accumulated digits to an integer, repeat the character that many times, and reset the digit buffer.
The solution
def decode(encoded: str) -> str:
result = ""
num_buffer = ""
for ch in encoded:
if ch.isdigit():
num_buffer += ch
else:
count = int(num_buffer)
for _ in range(count):
result += ch
num_buffer = ""
return resultCommon follow-up questions
- What if the count is missing (implying 1)? (Tests adding a default: if `num_buffer` is empty when a letter is found, treat count as 1.)
- How would you encode a string back into this format? (Tests the inverse: tracking consecutive runs and writing count+char pairs.)
- What if the input contains invalid format like consecutive letters? (Tests error handling and input validation.)