#1569

Number of Ways to Reorder Array to Get Same BST

Hard
ArrayMathDivide and ConquerDynamic ProgrammingTreeUnion-FindBinary Search TreeMemoizationCombinatoricsBinary TreeDivide and ConquerDynamic ProgrammingCombinatorics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach uses a divide-and-conquer strategy to count the number of valid BSTs that can be formed with the left and right subtrees of the root. It utilizes combinatorial mathematics to efficiently calculate the number of ways to arrange elements.

⚙️

Algorithm

4 steps
  1. 1Step 1: Identify the root (the first element of the array).
  2. 2Step 2: Partition the remaining elements into left and right subtrees based on their values relative to the root.
  3. 3Step 3: Recursively calculate the number of valid arrangements for the left and right subtrees.
  4. 4Step 4: Use combinatorial math (binomial coefficients) to calculate the number of ways to interleave the left and right subtree arrangements.
solution.py21 lines
1from math import comb
2
3MOD = 10**9 + 7
4
5def count_same_bst(nums):
6    def count_ways(start, end):
7        if start >= end:
8            return 1
9        root = nums[start]
10        left = [x for x in nums[start + 1:end + 1] if x < root]
11        right = [x for x in nums[start + 1:end + 1] if x > root]
12        left_count = count_ways(start + 1, start + len(left))
13        right_count = count_ways(start + len(left) + 1, end)
14        total_count = (left_count * right_count) % MOD
15        total_count = (total_count * comb(len(left) + len(right), len(left))) % MOD
16        return total_count
17
18    return count_ways(0, len(nums) - 1)
19
20# Example usage:
21print(count_same_bst([2, 1, 3]))  # Output: 1

Complexity note: The time complexity is O(n²) due to the recursive calls for counting left and right subtrees, while the space complexity is O(n) due to the recursion stack.

  • 1The first element of the array is always the root of the BST.
  • 2The arrangement of left and right subtrees can be calculated using combinatorial mathematics.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.