- 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
- 32 lines of C++ from the credited upstream file 106.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 1 loop block 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* buildTree(vector<int>& inorder, vector<int>& postorder) {4 unordered_map<int, int> inToIndex;5 6 for (int i = 0; i < inorder.size(); ++i)7 inToIndex[inorder[i]] = i;8 9 return build(inorder, 0, inorder.size() - 1, postorder, 0,10 postorder.size() - 1, inToIndex);11 }12 13 private:14 TreeNode* build(const vector<int>& inorder, int inStart, int inEnd,15 const vector<int>& postorder, int postStart, int postEnd,16 const unordered_map<int, int>& inToIndex) {17 if (inStart > inEnd)18 return nullptr;19 20 const int rootVal = postorder[postEnd];21 const int rootInIndex = inToIndex.at(rootVal);22 const int leftSize = rootInIndex - inStart;23 24 TreeNode* root = new TreeNode(rootVal);25 root->left = build(inorder, inStart, rootInIndex - 1, postorder, postStart,26 postStart + leftSize - 1, inToIndex);27 root->right = build(inorder, rootInIndex + 1, inEnd, postorder,28 postStart + leftSize, postEnd - 1, inToIndex);29 return root;30 }31};32