Skip to content

Ternary Expression

Jessica Sang edited this page Sep 14, 2024 · 1 revision

TIP102 Unit 7 Session 1 Advanced (Click for link to problem statements)

Problem 6: Ternary Expression

Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return its result as a string.

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 30 mins
  • 🛠️ Topics: Recursion, String Parsing, Ternary Expression Evaluation

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • Q: What is the main task in this problem?
    • A: The task is to evaluate an arbitrarily nested ternary expression and return the result as a string.
  • Q: How are the ternary expressions structured?
    • A: Ternary expressions use the syntax condition ? true_choice : false_choice, and they group right-to-left.
HAPPY CASE
Input: "T?2:3"
Output: "2"
Explanation: If True, then result is 2; otherwise result is 3.

Input: "F?1:T?4:5"
Output: "4"
Explanation: The conditional expressions group right-to-left, and the result is "4".

Input: "T?T?F:5:3"
Output: "F"
Explanation: The conditional expressions group right-to-left, and the result is "F".

EDGE CASE
Input: "F?9:T?F:0"
Output: "0"
Explanation: The conditional expressions group right-to-left, and the result is "0".

2: M-atch

Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.

For Evaluating Ternary Expressions, we want to consider the following approaches:

  • Recursive Parsing: Recursively parse the string, evaluating the condition and choosing the correct branch to evaluate next.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea:

  • We can recursively evaluate the ternary expression by checking the condition and then deciding which part of the expression to evaluate next. This approach naturally handles the nested structure by making recursive calls.

Recursive Approach:

1) Define a helper function that takes an index `i` and returns the evaluated result of the expression starting from that index, along with the updated index.
2) If the current character at index `i` is not `T`, `F`, or `?`, it must be a digit or a boolean result; return it.
3) If the current character is a condition (either `T` or `F`), skip the next character (`?`) and recursively evaluate the true expression.
4) Skip the `:` character and recursively evaluate the false expression.
5) Return the result based on whether the condition is `T` or `F`.
6) Start the recursive evaluation from the first character of the expression.

⚠️ Common Mistakes

  • Misinterpreting the nesting of the expressions due to the right-to-left grouping.
  • Forgetting to skip over the ? and : characters correctly, leading to incorrect parsing.

4: I-mplement

Implement the code to solve the algorithm.

def evaluate_ternary_expression_recursive(expression):
    def helper(i):
        # Base case: return a digit or boolean value if it's just that
        if i >= len(expression) or expression[i] not in 'TF?':
            return expression[i], i
        
        # Current character should be a condition (either 'T' or 'F')
        condition = expression[i]
        i += 2  # Skip over '?' after the condition
        
        # Recursively evaluate the true_expression
        true_result, i = helper(i)
        
        # Skip over the ':' separating true and false expressions
        i += 1
        
        # Recursively evaluate the false_expression
        false_result, i = helper(i)
        
        # Return the appropriate result based on the condition
        if condition == 'T':
            return true_result, i
        else:
            return false_result, i
    
    # Start the recursive evaluation from the first character
    result, _ = helper(0)
    return result

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

  • Trace through the evaluate_ternary_expression_recursive function with the input "T?2:3". The function should return "2" after evaluating the ternary expression.
  • Test the function with edge cases like "F?1:T?4:5". The function should return "4" after correctly grouping and evaluating the expression right-to-left.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Time Complexity:

  • Time Complexity: O(N), where N is the length of the string. The function processes each character exactly once.
  • Space Complexity: O(N), due to the recursion stack. The depth of recursion is proportional to the nesting level of the ternary expressions.

Discussion:

  • This recursive approach effectively handles the nested ternary expression by evaluating the conditions and selecting the appropriate branches to evaluate next.
  • An iterative approach with a stack, as given, might be more efficient in terms of space usage, but the recursive approach is more natural and easier to understand for recursive problems like this one.
Clone this wiki locally