- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 45 lines of Python from the credited upstream file 736.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def evaluate(self, expression: str) -> int:3 def evaluate(e: str, prevScope: dict) -> int:4 if e[0].isdigit() or e[0] == '-':5 return int(e)6 if e in prevScope:7 return prevScope[e]8 9 scope = prevScope.copy()10 nextExpression = e[e.index(' ') + 1:-1]11 tokens = parse(nextExpression)12 13 if e[1] == 'm': 14 return evaluate(tokens[0], scope) * evaluate(tokens[1], scope)15 if e[1] == 'a': 16 return evaluate(tokens[0], scope) + evaluate(tokens[1], scope)17 18 19 for i in range(0, len(tokens) - 2, 2):20 scope[tokens[i]] = evaluate(tokens[i + 1], scope)21 22 return evaluate(tokens[-1], scope)23 24 def parse(e: str):25 tokens = []26 s = ''27 opened = 028 29 for c in e:30 if c == '(':31 opened += 132 elif c == ')':33 opened -= 134 if opened == 0 and c == ' ':35 tokens.append(s)36 s = ''37 else:38 s += c39 40 if len(s) > 0:41 tokens.append(s)42 return tokens43 44 return evaluate(expression, {})45