- 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
- 34 lines of C++ from the credited upstream file 889.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* constructFromPrePost(vector<int>& pre, vector<int>& post) {4 unordered_map<int, int> postToIndex;5 6 for (int i = 0; i < post.size(); ++i)7 postToIndex[post[i]] = i;8 9 return build(pre, 0, pre.size() - 1, post, 0, post.size() - 1, postToIndex);10 }11 12 private:13 TreeNode* build(const vector<int>& pre, int preStart, int preEnd,14 const vector<int>& post, int postStart, int postEnd,15 const unordered_map<int, int>& postToIndex) {16 if (preStart > preEnd)17 return nullptr;18 if (preStart == preEnd)19 return new TreeNode(pre[preStart]);20 21 const int rootVal = pre[preStart];22 const int leftRootVal = pre[preStart + 1];23 const int leftRootPostIndex = postToIndex.at(leftRootVal);24 const int leftSize = leftRootPostIndex - postStart + 1;25 26 TreeNode* root = new TreeNode(rootVal);27 root->left = build(pre, preStart + 1, preStart + leftSize, post, postStart,28 leftRootPostIndex, postToIndex);29 root->right = build(pre, preStart + leftSize + 1, preEnd, post,30 leftRootPostIndex + 1, postEnd - 1, postToIndex);31 return root;32 }33};34