- 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
- 45 lines of Java from the credited upstream file 1932.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 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 Solution {2 public TreeNode canMerge(List<TreeNode> trees) {3 Map<Integer, TreeNode> valToNode = new HashMap<>(); 4 Map<Integer, Integer> count = new HashMap<>(); 5 6 for (TreeNode tree : trees) {7 valToNode.put(tree.val, tree);8 count.merge(tree.val, 1, Integer::sum);9 if (tree.left != null)10 count.merge(tree.left.val, 1, Integer::sum);11 if (tree.right != null)12 count.merge(tree.right.val, 1, Integer::sum);13 }14 15 for (TreeNode tree : trees)16 if (count.get(tree.val) == 1) {17 if (isValidBST(tree, null, null, valToNode) && valToNode.size() <= 1)18 return tree;19 return null;20 }21 22 return null;23 }24 25 private boolean isValidBST(TreeNode tree, TreeNode minNode, TreeNode maxNode,26 Map<Integer, TreeNode> valToNode) {27 if (tree == null)28 return true;29 if (minNode != null && tree.val <= minNode.val)30 return false;31 if (maxNode != null && tree.val >= maxNode.val)32 return false;33 if (tree.left == null && tree.right == null && valToNode.containsKey(tree.val)) {34 final int val = tree.val;35 tree.left = valToNode.get(val).left;36 tree.right = valToNode.get(val).right;37 valToNode.remove(val);38 }39 40 return 41 isValidBST(tree.left, minNode, tree, valToNode) && 42 isValidBST(tree.right, tree, maxNode, valToNode);43 }44}45