Run-Length Decoder - Problem

Decode a run-length encoded string where consecutive identical characters are represented as count+character.

For example: 3a2b5c becomes aaabbccccc

The input string contains digits followed by letters. Multi-digit counts are supported (e.g., 12a means 12 'a' characters).

Handle invalid input gracefully:

  • Empty or null strings should return empty string
  • Invalid format (letter before digit, etc.) should return empty string
  • Zero counts (e.g., 0a) should be ignored

Input & Output

Example 1 — Basic Case
$ Input: encoded = "3a2b5c"
Output: "aaabbccccc"
💡 Note: 3 'a's + 2 'b's + 5 'c's = 'aaabbccccc'
Example 2 — Multi-digit Count
$ Input: encoded = "12a3b"
Output: "aaaaaaaaaaabbbb"
💡 Note: 12 'a's followed by 3 'b's
Example 3 — Invalid Format
$ Input: encoded = "3ab2"
Output: ""
💡 Note: Invalid: number not followed by single character

Constraints

  • 0 ≤ encoded.length ≤ 104
  • encoded contains only digits and English letters
  • Count values can be multi-digit (1-100)
  • Zero counts should be ignored

Visualization

Tap to expand
INPUTALGORITHMRESULTEncoded String"3a2b5c"Count-Character pairs3→a, 2→b, 5→c1Parse Numbers2Read Characters3Expand Repeats4Combine ResultsDecoded String"aaabbccccc"Total: 10 characters3 + 2 + 5 = 10Key Insight:Use a state machine to cleanly separate number parsing from characterexpansion, processing the string in a single efficient pass.TutorialsPoint - Run-Length Decoder | Single Pass State Machine
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen