Leetcode #1902: Depth of BST Given Insertion Order
In this guide, we solve Leetcode #1902 Depth of BST Given Insertion Order in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree. A binary search tree is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Binary Search Tree, Array, Binary Tree, Ordered Set
Intuition
The input is a tree, so recursive decomposition is a natural fit.
We can compute the answer by combining results from left and right subtrees.
Approach
Use DFS and pass the required state through recursive calls.
Combine child results to compute the answer for each node.
Steps:
- Pick traversal order.
- Recurse with state.
- Combine results from children.
Example
Input: order = [2,1,4,3]
Output: 3
Explanation: The binary search tree has a depth of 3 with path 2->3->4.
Python Solution
class Solution:
def maxDepthBST(self, order: List[int]) -> int:
sd = SortedDict({0: 0, inf: 0, order[0]: 1})
ans = 1
for v in order[1:]:
lower = sd.bisect_left(v) - 1
higher = lower + 1
depth = 1 + max(sd.values()[lower], sd.values()[higher])
ans = max(ans, depth)
sd[v] = depth
return ans
Complexity
The time complexity is O(n). The space complexity is O(h).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.