- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 60 lines of Python from the credited upstream file 1628.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from abc import ABC, abstractmethod2 3"""4This is the interface for the expression tree Node.5You should not remove it, and you can define some classes to implement it.6"""7 8 9class Node(ABC):10 @abstractmethod11 12 def evaluate(self) -> int:13 pass14 15 16class ExpNode(Node):17 op = {18 '+': lambda a, b: a + b,19 '-': lambda a, b: a - b,20 '*': lambda a, b: a * b,21 '/': lambda a, b: int(a / b),22 }23 24 def __init__(25 self,26 val: str,27 left: Optional['ExpNode'],28 right: Optional['ExpNode'],29 ):30 self.val = val31 self.left = left32 self.right = right33 34 def evaluate(self) -> int:35 if not self.left and not self.right:36 return int(self.val)37 return ExpNode.op[self.val](self.left.evaluate(), self.right.evaluate())38 39 40"""41This is the TreeBuilder class.42You can treat it as the driver code that takes the postinfix input43and returns the expression tree represnting it as a Node.44"""45 46 47class TreeBuilder(object):48 def buildTree(self, postfix: list[str]) -> 'Node':49 stack: list[ExpNode | None] = []50 51 for val in postfix:52 if val in '+-*/':53 right = stack.pop()54 left = stack.pop()55 stack.append(ExpNode(val, left, right))56 else:57 stack.append(ExpNode(val, None, None))58 59 return stack.pop()60