- 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
- 48 lines of Python from the credited upstream file 1214.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.
1class BSTIterator:2 def __init__(self, root: TreeNode | None, leftToRight: bool):3 self.stack = []4 self.leftToRight = leftToRight5 self._pushUntilNone(root)6 7 def hasNext(self) -> bool:8 return len(self.stack) > 09 10 def next(self) -> int:11 node = self.stack.pop()12 if self.leftToRight:13 self._pushUntilNone(node.right)14 else:15 self._pushUntilNone(node.left)16 return node.val17 18 def _pushUntilNone(self, root: TreeNode | None):19 while root:20 self.stack.append(root)21 root = root.left if self.leftToRight else root.right22 23 24class Solution:25 def twoSumBSTs(26 self,27 root1: TreeNode | None,28 root2: TreeNode | None,29 target: int,30 ) -> bool:31 bst1 = BSTIterator(root1, True)32 bst2 = BSTIterator(root2, False)33 34 l = bst1.next()35 r = bst2.next()36 while True:37 summ = l + r38 if summ == target:39 return True40 if summ < target:41 if not bst1.hasNext():42 return False43 l = bst1.next()44 else:45 if not bst2.hasNext():46 return False47 r = bst2.next()48