Problem Description
Given an insertion order of distinct integers (a permutation from 1 to n), simulate the insertion process into a binary search tree (BST). The BST is built by inserting the first element as the root and then inserting each subsequent number so that the BST properties hold. Return the depth (i.e. the number of nodes on the longest root-to-leaf path) of the final BST.
Key Insights
- When inserting a new value into a BST, its depth is determined by the depth of its immediate valid predecessor or successor in the BST.
- Use an auxiliary sorted container (or ordered set) to quickly locate the nearest inserted numbers (predecessor and successor).
- The new node’s depth is 1 plus the maximum depth of these two neighboring nodes.
- The problem can be solved in a single pass by updating the maximum depth as you simulated the insertions.
Space and Time Complexity
Time Complexity: O(n log n) on average with a balanced search approach, though worst-case using a sorted list might lean towards O(n^2) due to insertion costs.
Space Complexity: O(n) for storing the depths and the sorted list of inserted elements.
Solution
The idea is to simulate the BST insertion without explicitly constructing the complete tree structure. We maintain a sorted list (or ordered set) of the elements that have been inserted already along with a mapping from each value to its depth in the BST. For every new element, we determine its position in the sorted list (using binary search) and identify its closest lower and higher neighbors (if they exist). The new element’s depth will be the greater of these neighbors’ depths plus one. By tracking the maximum depth throughout the process, we obtain the final BST depth.