Parse Encoded String

MEDIUM

Write a Python function to parse an encoded string like "John000Doe000123" which contains a first name, last name, and an ID. These parts are separated by one or more zeros. The ID itself is guaranteed to contain no zeros. The function should return a dictionary like {"first_name": "John", "last_name": "Doe", "id": "123"}.

Assume there will always be exactly three parts (first name, last name, ID) separated by zeros.

Examples:

Example 1:

Input: encoded_string = "John000Doe000123"
Output: {'first_name': 'John', 'last_name': 'Doe', 'id': '123'}

Example 2:

Input: encoded_string = "Alice0Bob099"
Output: {'first_name': 'Alice', 'last_name': 'Bob', 'id': '99'}

Example 3 (Only ID, names are empty if string starts with zeros):

Input: encoded_string = "000000777"
Output: {'first_name': '', 'last_name': '', 'id': '777'} (If split results in empty strings for first/last name)

Constraints:

  • The input encoded_string will always be a string.
  • The ID part will not contain any '0' characters.
  • There will be at least one '0' separating parts if all parts are present.
  • The string structure implies two sequences of zeros separating three non-zero parts.

Function Signature (Python):

import re
from typing import Dict

class Solution:
    def parse_encoded_string(self, encoded_string: str) -> Dict[str, str]:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep