- 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
- 49 lines of Java from the credited upstream file 653.java.
- The implementation visibly relies on work queue.
- 2 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 public BSTIterator(TreeNode root, boolean leftToRight) {3 this.leftToRight = leftToRight;4 pushLeftsUntilNull(root);5 }6 7 public int next() {8 TreeNode root = stack.pop();9 pushLeftsUntilNull(leftToRight ? root.right : root.left);10 return root.val;11 }12 13 public boolean hasNext() {14 return !stack.isEmpty();15 }16 17 private Deque<TreeNode> stack = new ArrayDeque<>();18 private boolean leftToRight;19 20 private void pushLeftsUntilNull(TreeNode root) {21 while (root != null) {22 stack.push(root);23 root = leftToRight ? root.left : root.right;24 }25 }26}27 28class Solution {29 public boolean findTarget(TreeNode root, int k) {30 if (root == null)31 return false;32 33 BSTIterator left = new BSTIterator(root, true);34 BSTIterator right = new BSTIterator(root, false);35 36 for (int l = left.next(), r = right.next(); l < r;) {37 final int sum = l + r;38 if (sum == k)39 return true;40 if (sum < k)41 l = left.next();42 else43 r = right.next();44 }45 46 return false;47 }48}49