Count Insertion Orders That Produce the Same BST
Last updated: November 29, 2026
Quick Overview
Values are inserted one by one into an empty binary search tree. Given one insertion order (a permutation of 1 to n), count the other orderings that would produce an identical BST, modulo 10^9 + 7.
0
0
0 solved
Values are inserted one by one into an empty binary search tree. Given one insertion order (a permutation of 1 to n), count the other orderings that would produce an identical BST, modulo 10^9 + 7.
A Google onsite hard question mixing tree structure with combinatorics, framed around replaying a log of index insertions in a different order. The interviewer looks for the interleaving argument with binomial coefficients and a careful modular implementation.
What the Interviewer Expects
- Observe the first element must be the root
- Split the rest into left and right subsequences that preserve their own relative order
- Count interleavings with a binomial coefficient
- Recurse and multiply, subtracting one for the original order
- Precompute binomials or factorials modulo a prime
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Compute it iteratively to avoid deep recursion on sorted input.
- What is the answer for a perfectly balanced tree of 7 nodes?
- How does the count relate to the number of linear extensions of a tree poset?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list nums, a permutation of 1..n. Output: number of different permutations, excluding nums itself, whose insertion yields the same BST, modulo 10^9 + 7....
High-Level Design
The first inserted value is always the root, and it must come first in any valid order. The remaining values split into those smaller (left subtree) and larger (right subtree). Within each side, the r...