- 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
- 47 lines of C++ from the credited upstream file 1932.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 TreeNode* canMerge(vector<TreeNode*>& trees) {4 unordered_map<int, TreeNode*> valToNode; 5 unordered_map<int, int> count; 6 7 for (TreeNode* tree : trees) {8 valToNode[tree->val] = tree;9 ++count[tree->val];10 if (tree->left)11 ++count[tree->left->val];12 if (tree->right)13 ++count[tree->right->val];14 }15 16 for (TreeNode* tree : trees)17 if (count[tree->val] == 1) {18 if (isValidBST(tree, nullptr, nullptr, valToNode) &&19 valToNode.size() <= 1)20 return tree;21 return nullptr;22 }23 24 return nullptr;25 }26 27 private:28 bool isValidBST(TreeNode* tree, TreeNode* minNode, TreeNode* maxNode,29 unordered_map<int, TreeNode*>& valToNode) {30 if (tree == nullptr)31 return true;32 if (minNode && tree->val <= minNode->val)33 return false;34 if (maxNode && tree->val >= maxNode->val)35 return false;36 if (!tree->left && !tree->right && valToNode.contains(tree->val)) {37 const int val = tree->val;38 tree->left = valToNode[val]->left;39 tree->right = valToNode[val]->right;40 valToNode.erase(val);41 }42 43 return isValidBST(tree->left, minNode, tree, valToNode) &&44 isValidBST(tree->right, tree, maxNode, valToNode);45 }46};47