Problem solution · Python

Number of Ways to Reorder Array to Get Same Bst

Number of Ways to Reorder Array to Get Same Bst: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Number of Ways to Reorder Array to Get Same Bst, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 64 lines of Python from the credited upstream file number-of-ways-to-reorder-array-to-get-same-bst.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeNumber of Ways to Reorder Array to Get Same Bst · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n^2)# Space: O(n^2) MAX_N = 1000MOD = 10**9+7dp = [[0]*MAX_N for _ in xrange(MAX_N)]for i in xrange(len(dp)):    dp[i][0] = 1    for j in xrange(1, i+1):        dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%MOD  class Solution(object):    def numOfWays(self, nums):        """        :type nums: List[int]        :rtype: int        """        def iter_dfs(nums):            result = [0]            stk = [[1, [nums, result]]]            while stk:                step, params = stk.pop()                if step == 1:                    nums, ret = params                    if len(nums) <= 2:                        ret[0] = 1                        continue                    left = [v for v in nums if v < nums[0]]                    right = [v for v in nums if v > nums[0]]                    ret[0] = dp[len(left)+len(right)][len(left)]                    ret1, ret2 = [0], [0]                    stk.append([2, [ret1, ret2, ret]])                    stk.append([1, [right, ret2]])                    stk.append([1, [left, ret1]])                elif step == 2:                    ret1, ret2, ret = params                    ret[0] = ret[0]*ret1[0] % MOD                    ret[0] = ret[0]*ret2[0] % MOD            return result[0]         return (iter_dfs(nums)-1)%MOD  # Time:  O(n^2)# Space: O(n^2)class Solution(object):    def numOfWays(self, nums):        """        :type nums: List[int]        :rtype: int        """        def dfs(nums):            if len(nums) <= 2:                return 1            left = [v for v in nums if v < nums[0]]            right = [v for v in nums if v > nums[0]]            result = dp[len(left)+len(right)][len(left)]            result = result*dfs(left) % MOD            result = result*dfs(right) % MOD            return result         return (dfs(nums)-1)%MOD 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗