Ruby: array partitioning and combinatorics
Code\nruby\nMOD = 1_000_000_007\n\ndef num_of_ways(nums) = bst_permutations(nums) - 1\n\ndef bst_permutations(nums)\n  if nums.empty?\n    1\n  else\n    root_v
# Code\n```ruby\nMOD = 1_000_000_007\n\ndef num_of_ways(nums) = bst_permutations(nums) - 1\n\ndef bst_permutations(nums)\n  if nums.empty?\n    1\n  else\n    root_val = nums.shift\n    partitions = nums.partition { _1 < root_val }\n    comb(*partitions.map(&:size)) * partitions.map { bst_permutations _1 }.reduce(:*) % MOD\n  end\nend\n\ndef comb(a, b)\n  if a > b\n    comb(b, a)\n  else\n    (b + 1..b + a).reduce(1, :*) / (1..a).reduce(1, :*)\n  end\nend\n```\n\n# Time complexity\n\n$$\\mathcal{O}(n^2)$$\n\n# Space complexity\n\n$$\\mathcal{O}(n^2)$$
['Array', 'Math', 'Combinatorics', 'Ruby']