Decode a Run-Length Encoded String Where a Missing Count Means One
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Implement a decoder for run-length encoded strings in which each lowercase letter is followed by an optional repeat count, so that a5b3c becomes aaaaabbbc. It tests careful string parsing, multi-digit counts, letters written without a count, and writing your own test cases.
Read the full Apple Software Engineer interview experience this question came from
Constraints
- 1 <= len(s) <= 10^4
- s contains only lowercase English letters and the digits 0 to 9, and its first character is a letter
- Every count has no leading zero and satisfies 1 <= count <= 10^5
- The decoded string has length at most 10^5
- s is always a valid encoding: a sequence of tokens, each one lowercase letter optionally followed by a count
Examples
Input: ('a',)
Expected Output: 'a'
Explanation: Minimum valid input: a single bare letter (len(s) = 1) decodes to one copy of itself.
Input: ('z7',)
Expected Output: 'zzzzzzz'
Explanation: Degenerate: one token with an explicit one-digit count; seven z, output length 7.
Hints
- A count can have more than one digit, as in q10e; make sure you have read the whole count before you expand its letter.
- A letter with no digits after it stands for exactly one copy, and that includes a letter at the very end of the string.
- Each token is decoded on its own, so two neighbouring tokens with the same letter need no special handling.