- 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
- 31 lines of Java from the credited upstream file 889.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 TreeNode constructFromPrePost(int[] pre, int[] post) {3 Map<Integer, Integer> postToIndex = new HashMap<>();4 5 for (int i = 0; i < post.length; ++i)6 postToIndex.put(post[i], i);7 8 return build(pre, 0, pre.length - 1, post, 0, post.length - 1, postToIndex);9 }10 11 private TreeNode build(int[] pre, int preStart, int preEnd, int[] post, int postStart,12 int postEnd, Map<Integer, Integer> postToIndex) {13 if (preStart > preEnd)14 return null;15 if (preStart == preEnd)16 return new TreeNode(pre[preStart]);17 18 final int rootVal = pre[preStart];19 final int leftRootVal = pre[preStart + 1];20 final int leftRootPostIndex = postToIndex.get(leftRootVal);21 final int leftSize = leftRootPostIndex - postStart + 1;22 23 TreeNode root = new TreeNode(rootVal);24 root.left = build(pre, preStart + 1, preStart + leftSize, post, postStart, leftRootPostIndex,25 postToIndex);26 root.right = build(pre, preStart + leftSize + 1, preEnd, post, leftRootPostIndex + 1,27 postEnd - 1, postToIndex);28 return root;29 }30}31