Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1678. Goal Parser Interpretation - Leetcode Solution

Code Implementation

class Solution:
    def interpret(self, command: str) -> str:
        result = []
        i = 0
        while i < len(command):
            if command[i] == 'G':
                result.append('G')
                i += 1
            elif command[i:i+2] == '()':
                result.append('o')
                i += 2
            elif command[i:i+4] == '(al)':
                result.append('al')
                i += 4
        return ''.join(result)
      
class Solution {
public:
    string interpret(string command) {
        string result;
        for (size_t i = 0; i < command.length(); ) {
            if (command[i] == 'G') {
                result += 'G';
                i++;
            } else if (command.substr(i, 2) == "()") {
                result += 'o';
                i += 2;
            } else if (command.substr(i, 4) == "(al)") {
                result += "al";
                i += 4;
            }
        }
        return result;
    }
};
      
class Solution {
    public String interpret(String command) {
        StringBuilder result = new StringBuilder();
        int i = 0;
        while (i < command.length()) {
            if (command.charAt(i) == 'G') {
                result.append('G');
                i++;
            } else if (i + 1 < command.length() && command.substring(i, i + 2).equals("()")) {
                result.append('o');
                i += 2;
            } else if (i + 3 < command.length() && command.substring(i, i + 4).equals("(al)")) {
                result.append("al");
                i += 4;
            }
        }
        return result.toString();
    }
}
      
var interpret = function(command) {
    let result = '';
    for (let i = 0; i < command.length;) {
        if (command[i] === 'G') {
            result += 'G';
            i++;
        } else if (command.slice(i, i+2) === '()') {
            result += 'o';
            i += 2;
        } else if (command.slice(i, i+4) === '(al)') {
            result += 'al';
            i += 4;
        }
    }
    return result;
};
      

Problem Description

You are given a string called command that represents a sequence of instructions for a simple "Goal Parser." The command consists of the following patterns:

  • "G" should be interpreted as the string "G".
  • "()" should be interpreted as the string "o".
  • "(al)" should be interpreted as the string "al".

The task is to return the parsed string after replacing all occurrences of the above patterns according to the rules. The input string command is guaranteed to be valid and only contains the patterns described above, concatenated in any order.

Thought Process

When approaching this problem, the first idea might be to scan the string character by character and check for the presence of each pattern. Since there are only three possible patterns, we can compare substrings at each position to see if they match one of the patterns. This avoids the need for complicated parsing or regular expressions.

Initially, one might consider replacing all occurrences of "()" with "o" and "(al)" with "al" using built-in string replacement functions. However, since the patterns can overlap or appear in any order, a more careful scan is preferable for clarity and efficiency.

The key is to iterate through the string, look ahead as needed to identify which pattern is present, and build the result accordingly. This ensures that we interpret each part of the command exactly once and in the correct order.

Solution Approach

To solve the problem efficiently, we can use a simple loop to iterate through the command string:

  1. Initialize an empty result (string or list).
  2. Start at the beginning of the command string and use an index i to track our position.
  3. At each step:
    • If the character at i is 'G', append 'G' to the result and move i forward by 1.
    • If the substring starting at i is "()", append 'o' to the result and move i forward by 2.
    • If the substring starting at i is "(al)", append 'al' to the result and move i forward by 4.
  4. Repeat until the end of the string is reached.
  5. Return the joined result as the final interpreted string.

This approach is both simple and efficient because it only requires a single pass through the string and uses constant additional space.

Example Walkthrough

Let's consider the input command = "G()(al)".

  1. Start at index 0: command[0] = 'G'. Append 'G' to result. Move to index 1.
  2. At index 1: command[1:3] = "()". Append 'o' to result. Move to index 3.
  3. At index 3: command[3:7] = "(al)". Append 'al' to result. Move to index 7 (end of string).

The result after parsing is "Goal".

This process ensures each pattern is interpreted exactly once and in the correct order, producing the expected output.

Time and Space Complexity

Brute-force Approach: If we used repeated string replacements, each replacement would scan the string, potentially leading to higher time complexity, especially for long strings.

Optimized Approach (current):

  • Time Complexity: O(n), where n is the length of the input command string. We process each character at most once.
  • Space Complexity: O(n), for storing the result string.
This is optimal for this problem, as we must examine every character to interpret the command.

Summary

In summary, the Goal Parser Interpretation problem can be solved efficiently by scanning the input string once and checking for the three possible patterns at each step. By carefully advancing the index according to the matched pattern, we ensure a single-pass solution that is both easy to understand and optimal in terms of time and space. The solution is elegant because it leverages the limited and non-overlapping nature of the patterns, making the implementation straightforward and efficient.