Problem statement

https://binarysearch.com/problems/Parse-Ternary-Expression/

Solution

Equal to Leetcode 0439. Ternary Expression Parser.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, expression):
        stack = []
        
        for symb in expression.split()[::-1]:
            stack.append(symb) 
            while len(stack) > 4 and stack[-4] == ":" and stack[-2] == "?":
                last_5 = [stack.pop() for _ in range(5)]
                if last_5[0] == "false": 
                    stack.append(last_5[4])
                else: 
                    stack.append(last_5[2])
        return stack[0] == "true"