We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Goal Parser Interpretation

Number: 1797

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string command containing characters "G", "()", and "(al)", the task is to convert it into a new string based on the following rules: "G" becomes "G", "()" becomes "o", and "(al)" becomes "al". The converted strings are concatenated in the same order as they appear in the input command.


Key Insights

  • The mapping from patterns to outputs is straightforward.
  • We can iterate through the string and check for the specific patterns.
  • Care must be taken to correctly identify and move past the characters of multi-character patterns like "()" and "(al)".

Space and Time Complexity

Time Complexity: O(n) where n is the length of the input string since we traverse the string once. Space Complexity: O(n) for storing the output string.


Solution

The solution uses a simple iterative approach to scan through the input string character by character. When encountering 'G', it is directly appended to the result. When encountering an opening parenthesis '(', the next character(s) are examined:

  • If the next character is ')', it is detected as "()" which maps to "o".
  • Otherwise, it indicates the pattern "(al)", so "al" is added to the result. In each case, the index is incremented appropriately to skip the entire recognized pattern. This approach uses minimal additional data structures (just a result string) and straightforward conditional checks.

Code Solutions

# Python solution for Goal Parser Interpretation
def interpret(command: str) -> str:
    result = []  # List to collect characters, faster concatenation
    i = 0  # Initialize index pointer
    while i < len(command):
        if command[i] == 'G':
            result.append('G')  # Direct mapping for 'G'
            i += 1
        elif command[i] == '(':
            # Check if it is "()"
            if command[i+1] == ')':
                result.append('o')  # Mapping for "()"
                i += 2  # Skip both '(' and ')'
            else:
                result.append('al')  # Mapping for "(al)"
                i += 4  # Skip "(al)"
    return "".join(result)

# Example test cases
print(interpret("G()(al)"))   # Expected output: "Goal"
print(interpret("G()()()()(al)"))  # Expected output: "Gooooal"
print(interpret("(al)G(al)()()G"))  # Expected output: "alGalooG"
← Back to All Questions