question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
β | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
find-the-number-of-good-pairs-i | Super easy Python Solution| Beginner friendly | super-easy-python-solution-beginner-frie-pr6x | Code | rajsekhar5161 | NORMAL | 2025-03-28T15:30:59.786786+00:00 | 2025-03-28T15:30:59.786786+00:00 | 3 | false |
# Code
```python []
class Solution(object):
def numberOfPairs(self, num1, num2, k):
count=0
for i in range(len(num1)):
for j in range(len(num2)):
if num1[i]%(num2[j]*k)==0:
count+=1
return count
``` | 0 | 0 | ['Array', 'Hash Table', 'Python'] | 0 |
find-the-number-of-good-pairs-i | Divisible Detectives π΅οΈββοΈπ’ β Finding Good Pairs! | divisible-detectives-finding-good-pairs-6sqev | IntuitionThe problem requires us to find pairs ((i, j)) where the element from nums1 is divisible by the product of an element from nums2 and k. This suggests i | Shahin1212 | NORMAL | 2025-03-25T06:06:54.090839+00:00 | 2025-03-25T06:06:54.090839+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to find pairs \((i, j)\) where the element from `nums1` is divisible by the product of an element from `nums2` and `k`. This suggests iterating through all possible pairs and checking the divisibility condition.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Initialize a counter to keep track of the number of good pairs.
2. Use a nested loop:
- The outer loop iterates through each element in `nums1`.
- The inner loop iterates through each element in `nums2`.
- Check if `nums1[i]` is divisible by `nums2[j] * k`.
- If true, increment the counter.
3. Return the total count of good pairs.
# Complexity
- Time complexity:
- Since we iterate over every pair of elements from `nums1` and `nums2`, the worst-case time complexity is **O(n * m)**, where `n` is the length of `nums1` and `m` is the length of `nums2`.
- Space complexity:
- We only use a single integer variable (`count`), so the space complexity is **O(1)**.
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int],k:int)-> int:
count = 0
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i] % (nums2[j] * k) == 0:
count += 1
return count
```

| 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | Simple solution | simple-solution-by-mrwan54-rfww | Code | mrwan54 | NORMAL | 2025-03-24T22:26:19.306409+00:00 | 2025-03-24T22:26:19.306409+00:00 | 1 | false |
# Code
```cpp []
class Solution {
public:
int numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int res = 0;
size_t len1 = nums1.size(), len2 = nums2.size();
for (size_t i = 0; i < len1; ++i)
{
for (size_t j = 0; j < len2; ++j)
{
// is "good"
if (0 == (nums1[i] % (nums2[j] * k)))
{
++res;
}
}
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-the-number-of-good-pairs-i | β
[Python] USING HASHMAP, TC O(n + m) β
| python-using-hashmap-tc-on-m-by-rk_dp-4gfb | 1. Brute ForceTIme ComplexityO(n * M)Space ComplexityO(1)2. HashMapTIme ComplexityO(n + M)Space ComplexityO(1)Code | rk_dp | NORMAL | 2025-03-22T08:29:13.267993+00:00 | 2025-03-22T08:29:13.267993+00:00 | 2 | false | # **1. Brute Force**
# **TIme Complexity**
O(n * M)
# **Space Complexity**
O(1)
```
count = 0
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i] % (nums2[j] * k) == 0:
count += 1
return count
```
# **2. HashMap**
# **TIme Complexity**
O(n + M)
# **Space Complexity**
O(1)
# Code
```
count_map = Counter(num * k for num in nums2)
good_pairs = 0
for num in nums1:
for key in count_map:
if num % key == 0:
good_pairs += count_map[key]
return good_pairs
``` | 0 | 0 | ['Array', 'Hash Table', 'Python3'] | 0 |
find-the-number-of-good-pairs-i | πEasy C Language Solution Using Suitable Array Conceptsπ | easy-c-language-solution-using-suitable-t4qoa | IntuitionThe function calculates the number of pairs (nums1[i], nums2[j]) where the element from nums1 is divisible by k times the element from nums2. This invo | Vivek_Bartwal | NORMAL | 2025-03-22T06:59:35.389699+00:00 | 2025-03-22T06:59:35.389699+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The function calculates the number of pairs (nums1[i], nums2[j]) where the element from nums1 is divisible by k times the element from nums2. This involves checking each pair of elements from both arrays and applying the divisibility condition.
# Approach
<!-- Describe your approach to solving the problem. -->
1. **Initialize Count:**
Start with a count variable set to 0. This will keep track of valid pairs.
2. **Iterate Through Both Arrays:**
3. **Use a nested loop:**
Outer loop iterates over elements of nums1.
Inner loop iterates over elements of nums2.
4. **Check Divisibility:**
For each pair (nums1[i], nums2[j]), compute nums2[j] * k.
Check if nums1[i] % (nums2[j] * k) == 0 (i.e., nums1[i] is divisible by the scaled value).
If the condition is true, increment the count.
5. **Return Result:**
After iterating through all pairs, return the total count.
# Complexity
- Time complexity: O(n1.n2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
int numberOfPairs(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) {
int count = 0;
for(int i = 0; i <= nums1Size - 1; i++)
{
for(int j = 0; j <= nums2Size - 1; j++)
{
if(nums1[i] % (nums2[j] * k) == 0)
{
count++;
}
}
}
return count;
}
``` | 0 | 0 | ['Array', 'Hash Table', 'C'] | 0 |
find-the-number-of-good-pairs-i | π’ Count Valid Pairs | count-valid-pairs-by-akhildas675-ujrd | IntuitionThe problem requires us to find the number of valid pairs (i, j) such that:
nums1[i]modββ(nums2[j]Γk)==0
nums1[i]mod(nums2[j]Γk)==0My first thought was | akhildas675 | NORMAL | 2025-03-22T05:10:43.551660+00:00 | 2025-03-22T05:10:43.551660+00:00 | 3 | false | # Intuition
The problem requires us to find the number of valid pairs (i, j) such that:
nums1[i]modββ(nums2[j]Γk)==0
nums1[i]mod(nums2[j]Γk)==0
My first thought was to use a brute force approach: iterate through all possible (i, j) pairs and check the condition.
# Approach
1. Initialize count = 0 to store the number of valid pairs.
2. Use nested loops to iterate through all pairs (i, j):
β Outer loop: Traverse nums1.
β Inner loop: Traverse nums2.
β Check if nums1[i] % (nums2[j] * k) == 0.
β If true, increment count and optionally log the pair.
3. Return the total count of valid pairs.
# Complexity
β Time Complexity:
β O(nβ
m)O(nβ
m), where nn is the length of nums1 and mm is the length of nums2.
β This is because we iterate over all pairs (i, j).
β Space Complexity:
β O(1)O(1), as we use only a single count variable.
# Code
```javascript []
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var numberOfPairs = function(nums1, nums2, k) {
let count=0
for(let i=0;i<nums1.length;i++){
for(let j=0;j<nums2.length;j++){
if(nums1[i]%(nums2[j]*k)==0){
count++
console.log([i,j])
}
}
}
return count
};
```
β
Explanation with Example
Input:
nums1 = [10, 15, 20], nums2 = [2, 5], k = 2
Steps:
Pair checks:
β 10 % (5 * 2) == 10 % 10 == 0 β
β 15 % (2 * 2) == 15 % 4 == 3 β
β 15 % (5 * 2) == 15 % 10 == 5 β
β 20 % (2 * 2) == 20 % 4 == 0 β
β 20 % (5 * 2) == 20 % 10 == 0 β
Valid pairs:
β (10, 5)
β (20, 2)
β (20, 5)
Output:
3
π Why This Solution Works
β Brute-force but simple β Checks all pairs directly.
β No extra space used β Only one counter variable.
β Handles all cases correctly β Works for all k values.
π₯ Status: Accepted β
| 0 | 0 | ['JavaScript'] | 0 |
find-the-number-of-good-pairs-i | Easy Java Code | easy-java-code-by-sindhumandadapu24-wa2w | class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int c=0;
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if((nums | sindhumandadapu24 | NORMAL | 2025-03-18T08:43:58.222479+00:00 | 2025-03-18T08:43:58.222479+00:00 | 1 | false | class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int c=0;
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if((nums1[i]%(nums2[j]*k)==0)){
c++;
}
}
}
return c;
}
} | 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | LIST OF C# SOLUTION FOR SMALL AND LARGE ARRAYS (3 C# Solutions) | list-of-c-solution-for-small-and-large-a-ws7m | Intuition / Approach / ComplexityThis is an easy question, we can have a solution without using dictionary, just a brute force solution, we can iterate all nums | RachidBelouche | NORMAL | 2025-03-14T11:35:38.652048+00:00 | 2025-03-14T11:35:38.652048+00:00 | 4 | false | # Intuition / Approach / Complexity
<!-- Describe your first thoughts on how to solve this problem. -->
This is an easy question, we can have a solution without using dictionary, just a brute force solution, we can iterate all nums2 and change the number in nums2 to number * k (this will save time iterating all nums1 numbers and avoid doing multiplication, we just need to see the modulo of numbers from nums1), then we iterate all nums1 and we check the result of the modulo if it's equal to zero to increment our result variable, this will give us a time complexity of O(n * m) and space complexity of O(1).
We can reduce the time complexity to O(n * sqrt(max(nums1)) + m) if we use dictionary storing array nums2 times k having counter of occurance, then we calculate the factors (we can have other additional dictionary storing nums1 if we have duplicated numbers).
This is the case for problem 3164. Find the Number of Good Pairs II, but our problem 3162. Find the Number of Good Pairs I don't have many items in the arrays and duplicated numbers won't make the difference, but the other problem have large arrays which makes the usage of dictionary more usefull.
So I put the Dictionary Solution 1 & Dictionary Solution 2 which works for both problems (the only difference is the return type int and long).
Dictionary Solution 1 have one dictionary to store the nums2 times k with counter (space complexity is O(m)), while Dictionary Solution 2 have two dictionary to store nums2 times k and nums1 with counter(space complexity is O(n + m)).
[Solution For Problem 3164. Find the Number of Good Pairs II](https://leetcode.com/problems/find-the-number-of-good-pairs-ii/solutions/6535575/the-most-optimized-c-solution-explained-runtime-136ms-beats-100-00-memory-79-12mb-beats-100-00/)
# Code
```csharp [Brute Force Solution]
public class Solution {
public int NumberOfPairs(int[] nums1, int[] nums2, int k) {
int result = 0;
for(int j = 0; j < nums2.Length; j++){
nums2[j] *= k;
for(int i=0; i<nums1.Length; i++){
if(nums1[i] % nums2[j] == 0)
result++;
}
}
return result;
}
}
```
```csharp [Dictionary Solution 1]
public class Solution {
public int NumberOfPairs(int[] nums1, int[] nums2, int k) {
int result = 0;
Dictionary<int, int> f = new();
for(int i = 0; i < nums2.Length; i++){
if(!f.ContainsKey(nums2[i] * k))
f.Add(nums2[i] * k, 1);
else
f[nums2[i] * k]++;
}
for(int i = 0; i < nums1.Length; i++){
if(nums1[i] % k != 0)
continue;
int number = nums1[i];
int max = (int)Math.Sqrt(number);
for (int factor = 1; factor <= max; ++factor)
{
if (number % factor == 0)
{
result += f.ContainsKey(factor) ? f[factor] : 0;
if (factor != number/factor && f.ContainsKey(number/factor))
result += f[number/factor];
}
}
}
return result;
}
}
```
```csharp [Dictionary Solution 2]
public class Solution {
public int NumberOfPairs(int[] nums1, int[] nums2, int k) {
int result = 0;
Dictionary<int, int> f = new();
for(int i = 0; i < nums2.Length; i++){
nums2[i] = nums2[i] * k;
if(!f.ContainsKey(nums2[i]))
f.Add(nums2[i], 1);
else
f[nums2[i]]++;
}
Dictionary<int, int> n1 = new();
for(int i = 0; i < nums1.Length; i++){
if(!n1.ContainsKey(nums1[i]))
n1.Add(nums1[i], 1);
else
n1[nums1[i]]++;
}
foreach(var kvp in n1){
if(kvp.Key % k != 0)
continue;
int r = 0;
int max = (int)Math.Sqrt(kvp.Key);
for (int factor = 1; factor <= max; factor++)
{
if (kvp.Key % factor == 0)
{
if(f.ContainsKey(factor))
r += f[factor];
if (factor != kvp.Key/factor && f.ContainsKey(kvp.Key/factor))
r += f[kvp.Key/factor];
}
}
result += (r * kvp.Value);
}
return result;
}
}
``` | 0 | 0 | ['Array', 'Hash Table', 'Counting', 'Number Theory', 'C#'] | 0 |
find-the-number-of-good-pairs-i | Simple solution in Java. Beats 100 % | simple-solution-in-java-beats-100-by-kha-qb6o | Complexity
Time complexity:
O(m * n)
Space complexity:
O(1)
Code | Khamdam | NORMAL | 2025-03-13T09:41:41.541160+00:00 | 2025-03-13T09:41:41.541160+00:00 | 2 | false | # Complexity
- Time complexity:
O(m * n)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int goodPairs = 0;
int n = nums1.length;
int m = nums2.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (nums1[i] % (nums2[j] * k) == 0) {
goodPairs++;
}
}
}
return goodPairs;
}
}
``` | 0 | 0 | ['Array', 'Java'] | 0 |
find-the-number-of-good-pairs-i | Simple solution - beats 100%π₯ | simple-solution-beats-100-by-cyrusjetson-z01i | Complexity
Time complexity: O(N * N)
Space complexity: O(N)
Code | cyrusjetson | NORMAL | 2025-03-13T09:04:52.551458+00:00 | 2025-03-13T09:04:52.551458+00:00 | 1 | false | # Complexity
- Time complexity: O(N * N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int count = 0;
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) == 0) count++;
}
}
return count;
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | Easy Java Solution | easy-java-solution-by-prachijain-9p63 | IntuitionApproachComplexity
Time complexity:
O(n*m)
Space complexity:
O(1)
Code | prachijain | NORMAL | 2025-03-08T14:37:59.032503+00:00 | 2025-03-08T14:37:59.032503+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n*m)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int count = 0;
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) == 0) {
count++;
}
}
}
return count;
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | Simple solution - beats 100% π₯ | simple-solution-beats-100-by-joshuaimman-vl1p | Complexity
Time complexity : O(N * M)
Space complexity: O(1)
Code | joshuaimmanuelin | NORMAL | 2025-03-08T07:36:54.653338+00:00 | 2025-03-08T07:36:54.653338+00:00 | 1 | false |
# Complexity
- Time complexity : O(N * M)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int goodPair = 0;
for (int i = 0;i < nums1.length; i++) {
int rs1 = nums1[i];
for (int j = 0; j < nums2.length; j++) {
int rs2 = nums2[j];
if (rs1 % (rs2 * k) == 0) {
goodPair += 1;
}
}
}
return goodPair;
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | Very Easy and Simple | very-easy-and-simple-by-yashu__007-ci2o | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Yashu__007 | NORMAL | 2025-03-08T06:44:57.975055+00:00 | 2025-03-08T06:44:57.975055+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
c=0
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i]%(nums2[j]*k)==0:
c+=1
return c
``` | 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | test_from_immortal | test_from_immortal-by-immortal_039-4eph | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Immortal_039 | NORMAL | 2025-03-07T20:32:32.015342+00:00 | 2025-03-07T20:32:32.015342+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
good = 0
for i in nums1:
for j in nums2:
if i % (j * k) == 0:
good += 1
return good
``` | 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | Easy || JavaScript | easy-javascript-by-mohdaman7-qs94 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Mohdaman7 | NORMAL | 2025-03-06T06:55:21.132536+00:00 | 2025-03-06T06:55:21.132536+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var numberOfPairs = function(nums1, nums2, k) {
let count = 0;
for(let i=0;i<nums1.length;i++){
for(let j=0;j<nums2.length;j++){
if(nums1[i]%(nums2[j]*k)==0){
count++
}
}
}
return count
};
``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-number-of-good-pairs-i | Easy-Javascript!!! | easy-javascript-by-nishanaaaah-gkzo | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | nishanaaaah | NORMAL | 2025-03-06T05:36:23.741817+00:00 | 2025-03-06T05:36:23.741817+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var numberOfPairs = function(nums1, nums2, k) {
let count = 0;
for(let i=0;i<nums1.length;i++){
for(let j=0;j<nums2.length;j++){
let int = nums2[j]*k
if(nums1[i]%int==0){
count++
}
}
}
return count
};
``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-number-of-good-pairs-i | My submission beat 100% of other submissions' runtime. | my-submission-beat-100-of-other-submissi-l70m | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | limon4ik13 | NORMAL | 2025-03-05T11:52:40.697184+00:00 | 2025-03-05T11:52:40.697184+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
#include<unordered_map>
class Solution {
public:
int numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
unordered_map<int, int> keys;
int count = 0;
for(int i = 0;i<nums2.size();i++){
keys[nums2[i]*k]+=1;
}
for(int i = 0; i<nums1.size();i++){
for(const auto& [key, value]:keys){
if(nums1[i]%key == 0)
count += value;
}
}
return count;
}
};
``` | 0 | 0 | ['Hash Table', 'C++'] | 0 |
find-the-number-of-good-pairs-i | Simple Java Solution Beats 100% | simple-java-solution-beats-100-by-sairaj-r1k9 | Code | Sairaj_Thakar | NORMAL | 2025-02-24T15:28:51.946116+00:00 | 2025-02-24T15:28:51.946116+00:00 | 3 | false | # Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int res = 0;
for(int i = 0; i<nums1.length; i++)
{
int out= nums1[i];
for(int j =0; j<nums2.length; j++)
{
int inn = nums2[j];
if(out % (inn*k) == 0)
{
res++;
}
}
}
return res;
}
}
```

| 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | Using for loop | using-for-loop-by-vijayakumar-1728-dhxc | Code | vijayakumar-1728 | NORMAL | 2025-02-22T15:02:57.697827+00:00 | 2025-02-22T15:02:57.697827+00:00 | 1 | false |
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int n=nums1.length;
int m=nums2.length;
int c=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(nums1[i]%(nums2[j]*k)==0){
c++;
}
}
}
return c;
}
}
``` | 0 | 0 | ['Java'] | 0 |
find-the-number-of-good-pairs-i | Brute Force | brute-force-by-meky20500-ywva | IntuitionApproachComplexity
Time complexity: O(n^2)
Space complexity:O(1)
Code | meky20500 | NORMAL | 2025-02-19T20:26:39.504336+00:00 | 2025-02-19T20:26:39.504336+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int NumberOfPairs(int[] nums1, int[] nums2, int k) {
int ans = 0;
for(int i = 0; i < nums1.Length; i++)
for(int j = 0; j < nums2.Length; j++)
if(nums1[i] % (nums2[j]*k) == 0)
ans++;
return ans;
}
}
``` | 0 | 0 | ['Array', 'C#'] | 0 |
find-the-number-of-good-pairs-i | Most Easy Python Solution[Beats 100%] | most-easy-python-solutionbeats-100-by-gn-0mtp | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | gnishant9761 | NORMAL | 2025-02-17T19:04:55.367737+00:00 | 2025-02-17T19:04:55.367737+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums1=list(filter(lambda x: x%k==0, nums1))
count=0
for i,val1 in enumerate(nums1):
for j,val2 in enumerate(nums2):
if val1%(val2*k)==0:
count+=1
return count
``` | 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | base solution js | base-solution-js-by-kovalvladik-bszp | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | kovalvladik | NORMAL | 2025-02-17T16:15:12.802981+00:00 | 2025-02-17T16:15:12.802981+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var numberOfPairs = function(nums1, nums2, k) {
let result = 0;
for(let i = 0; i<nums1.length; i++){
for(let j = 0; j<nums2.length; j++){
if((nums1[i] % (nums2[j]*k)) == 0){
result++;
}
}
}
return result;
};
``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-number-of-good-pairs-i | Runtime 3 ms Beats 89.11% | runtime-3-ms-beats-8911-by-ajithajk46-bpov | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ajithajk46 | NORMAL | 2025-02-17T06:36:31.202199+00:00 | 2025-02-17T06:36:31.202199+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
res = 0
for i in nums1:
for j in nums2:
if i % (j * k) == 0:
res += 1
return res
``` | 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | easy solution | easy-solution-by-haneen_ep-4jem | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | haneen_ep | NORMAL | 2025-02-17T05:23:53.646565+00:00 | 2025-02-17T05:23:53.646565+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number}
*/
var numberOfPairs = function (nums1, nums2, k) {
let pairs = 0;
for (let i = 0; i < nums1.length; i++) {
for (let j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) === 0) {
pairs++
}
}
}
return pairs
};
``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-number-of-good-pairs-i | EASY PYTHON CODE | easy-python-code-by-vishnuande2006-kjy7 | Code | vishnuande2006 | NORMAL | 2025-02-16T09:46:42.846540+00:00 | 2025-02-16T09:46:42.846540+00:00 | 2 | false |
# Code
```python3 []
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
c = 0
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i]%(nums2[j]*k) == 0:
c += 1
return c
``` | 0 | 0 | ['Python3'] | 0 |
find-the-number-of-good-pairs-i | Java&JS&TS Solution (JW) | javajsts-solution-jw-by-specter01wj-rlyj | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | specter01wj | NORMAL | 2025-02-12T23:26:59.851516+00:00 | 2025-02-12T23:26:59.851516+00:00 | 10 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int count = 0;
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) == 0) {
count++;
}
}
}
return count;
}
```
```javascript []
var numberOfPairs = function(nums1, nums2, k) {
let count = 0;
for (let i = 0; i < nums1.length; i++) {
for (let j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) === 0) {
count++;
}
}
}
return count;
};
```
```typescript []
function numberOfPairs(nums1: number[], nums2: number[], k: number): number {
let count = 0;
for (let i = 0; i < nums1.length; i++) {
for (let j = 0; j < nums2.length; j++) {
if (nums1[i] % (nums2[j] * k) === 0) {
count++;
}
}
}
return count;
};
``` | 0 | 0 | ['Array', 'Hash Table', 'Java', 'TypeScript', 'JavaScript'] | 0 |
find-the-number-of-good-pairs-i | Simple brute force implementation (BEATS 100%) | simple-brute-force-implementation-beats-nk32x | Complexity
Time complexity:
Space complexity:
Code | Aashif_AK | NORMAL | 2025-02-12T11:18:43.413920+00:00 | 2025-02-12T11:18:43.413920+00:00 | 0 | false |
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int numberOfPairs(int[] nums1, int[] nums2, int k) {
int x = 0;
for (int i=0; i<nums1.length;i++){
for (int j=0; j<nums2.length;j++){
if(nums1[i] % (nums2[j] * k) == 0) x++;
}
}
return x;
}
}
``` | 0 | 0 | ['Java'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | [C++]--Just using recursion, very Clean and Easy to understand--O(n^2) | c-just-using-recursion-very-clean-and-ea-j89c | So, we can know that for a fixed root, the left subtree elements and the right subtree elements are also fixed.\n\nWe can find the left subtree elements which a | aincrad-lyu | NORMAL | 2020-08-30T04:13:32.314186+00:00 | 2020-08-30T08:51:26.622799+00:00 | 20,336 | false | So, we can know that for a fixed root, the left subtree elements and the right subtree elements are also fixed.\n\nWe can find the ``left subtree elements`` which are all the elements that is **smaller** than root value, and ``right subtree elements`` which are **greater** than root value.\n\nAnd in order to make it identical with original BST, we should **keep the relative order** in left subtree elements and in right subtree elements.\n\nAssume the lenght of left subtree elements is ``left_len`` and right is ``right_len``, they **can change their absolute position** but **need to keep their relative position** in either left subtree or right right subtree. \n\nSo as the subtree, so we use recursion.\n\n**Example**\n```\n[3, 4, 5, 1, 2] // original array with root value is 3\n\n[1, 2] // left sub-sequence, left_len = 2\n[4, 5] // right sub-sequence, right_len = 2\n\n// the left sub-sequence and right sub-sequence take 4 position, because left_len + right_len = 4\n\n// keep relative order in left sub-sequence and in right-sequence, but can change absolute position.\n[1, 2, 4, 5]\n[1, 4, 2, 5]\n[1, 4, 5, 2]\n[4, 1, 2, 5]\n[4, 1, 5, 2]\n[4, 5, 1, 2]\n// number of permutation: 6\n\n// in code, we use Pascal triangle to keep a table of permutations, so we can look up the table and get permutation result in O(1)\n```\n\n**Code**\n```\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) {\n long long mod = 1e9 + 7;\n\t\tint n = nums.size();\n \n\t\t// Pascal triangle\n table.resize(n + 1);\n for(int i = 0; i < n + 1; ++i){\n table[i] = vector<long long>(i + 1, 1);\n for(int j = 1; j < i; ++j){\n table[i][j] = (table[i-1][j-1] + table[i-1][j]) % mod;\n }\n }\n \n long long ans = dfs(nums, mod);\n return ans % mod - 1;\n }\n \nprivate:\n vector<vector<long long>> table;\n long long dfs(vector<int> &nums, long long mod){\n int n = nums.size();\n if(n <= 2) return 1;\n \n\t\t// find left sub-sequence elements and right sub-sequence elements\n vector<int> left, right;\n for(int i = 1; i < nums.size(); ++i){\n if(nums[i] < nums[0]) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n }\n\t\t\n\t\t// recursion with left subtree and right subtree\n long long left_res = dfs(left, mod) % mod;\n long long right_res = dfs(right, mod) % mod;\n\t\t\n\t\t// look up table and multiple them together\n\t\tint left_len = left.size(), right_len = right.size();\n return (((table[n - 1][left_len] * left_res) % mod) * right_res) % mod;\n }\n};\n``` | 167 | 1 | [] | 19 |
number-of-ways-to-reorder-array-to-get-same-bst | Python in 6 short lines with easy explanation | python-in-6-short-lines-with-easy-explan-i3yw | We separate all the elements into two lists, depending on whether they are less than or more than the root. Then we recurse on those left and right sublists. | daciuk | NORMAL | 2020-08-30T04:06:35.358544+00:00 | 2020-08-30T04:11:28.620463+00:00 | 9,670 | false | We separate all the elements into two lists, depending on whether they are less than or more than the root. Then we recurse on those left and right sublists. The combination is for the macro ordering between left and right, and the recursive factors are for the internal ordering of left and right themselves. I minus 1 from the result because we don\'t count the original ordering.\n\n```\ndef numOfWays(self, nums: List[int]) -> int:\n def f(nums):\n if len(nums) <= 2: return 1\n left = [v for v in nums if v < nums[0]]\n right = [v for v in nums if v > nums[0]]\n return comb(len(left)+len(right), len(right)) * f(left) * f(right)\n return (f(nums)-1) % (10**9+7)\n``` | 119 | 3 | [] | 10 |
number-of-ways-to-reorder-array-to-get-same-bst | Python π Easy & Fast Solution | python-easy-fast-solution-by-souvik_bane-xr81 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nHere are my initial thoughts on how to solve this problem:\n\n- The base case of the | Souvik_Banerjee-2020 | NORMAL | 2023-06-16T02:15:50.003331+00:00 | 2023-06-16T02:15:50.003349+00:00 | 7,859 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nHere are my initial thoughts on how to solve this problem:\n\n- The base case of the recursive function f is when the length of the input list nums is less than or equal to 2, in which case there is only one way to arrange the numbers. This is returned as 1.\n\n- The recursive case involves splitting the list nums into two sublists: left and right. The left sublist contains numbers smaller than the first element of nums, while the right sublist contains numbers greater than the first element.\n\n- The number of ways to arrange the numbers in nums is calculated as the product of three factors:\n\n- The number of ways to choose the positions for the right sublist among the total number of positions (i.e., combinations of the lengths of left and right).\n- The number of ways to arrange the numbers in the left sublist.\n- The number of ways to arrange the numbers in the right sublist.\n\n- The recursive calls to f are made on the left and right sublists to compute the number of ways to arrange their respective numbers.\n\n- Finally, the result is obtained by subtracting 1 from the total number of ways and taking the modulus with (10**9 + 7).\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe numOfWays function calculates the number of ways to arrange the given list of numbers by recursively calling the helper function f.\n\nThe recursive function f performs the following steps:\n\n- It checks for the base case: if the length of the input list nums is less than or equal to 2, indicating that there is only one way to arrange the numbers, it returns 1.\n\n- For the recursive case, the function splits the input list nums into two sublists: left and right. The left sublist contains all the numbers smaller than the first element of nums, while the right sublist contains all the numbers greater than the first element.\n\n- The number of ways to arrange the numbers in nums is calculated as follows:\n\n- Determine the number of positions available for the right sublist by combining the lengths of the left and right sublists using the comb function from the math module.\n\n- Multiply the above value by the number of ways to arrange the numbers in the left sublist (by making a recursive call to f).\n\n- Multiply the result by the number of ways to arrange the numbers in the right sublist (also by making a recursive call to f).\n\n- The final result is obtained by subtracting 1 from the total number of ways calculated and taking the modulus with (10**9 + 7).\n\n## To improve the code:\n\nImport the comb function from the math module.\nUse proper formatting and indentation to enhance code readability.\nTesting the code with different inputs and comparing the results against expected outcomes would be crucial to ensure the correctness of the implementation.\n\n\n# Complexity\n- Time complexity:$$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom math import comb\nfrom typing import List\n\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n def f(nums):\n if len(nums) <= 2:\n return 1\n left = [v for v in nums if v < nums[0]]\n right = [v for v in nums if v > nums[0]]\n return comb(len(left) + len(right), len(right)) * f(left) * f(right)\n \n return (f(nums) - 1) % (10**9 + 7)\n\n```\n\n\n | 65 | 0 | ['Array', 'Math', 'Divide and Conquer', 'Dynamic Programming', 'Python3'] | 10 |
number-of-ways-to-reorder-array-to-get-same-bst | [Java] Clean code uses Yang Hui's/Pascal's Triangle With Explanation | java-clean-code-uses-yang-huispascals-tr-ovoz | This is actually a mathematical problem that can be solved by combination calculation, what\'d you do is basically arranging left and right sub-trees in correct | chyyyy | NORMAL | 2020-08-30T07:34:26.532546+00:00 | 2020-08-30T23:34:56.325906+00:00 | 7,118 | false | This is actually a mathematical problem that can be solved by combination calculation, what\'d you do is basically arranging left and right sub-trees in correct order but in all possible combinations.\nFor example for array ```[3,6,4,1]```\n```\n[3,6,4,1] left sub tree is [1], right tree is [6,4], \nwe just need to keep 6 appear in front of 4 to make permutation a valid one,\nso combinations can be [6,4,1], [6,1,4], [1,6,4]\nObviously, if left sub tree length is 1 and total length is 3, combination is 3C1 which is 3\n```\nExpand to a more complicated case ```[3,6,4,1,7]```\n```\nleft sub tree is [1], right tree is [6,4,7], \npermutations for right tree itself is [6,4,7], [6,7,4] which means it\'s 2C1 (combination of [4] and [7])\nfor every permuration of right tree you can also combine it with left tree [1] so total # is 4C1*2C1=8\n```\nTseudo code:\n```\ndef dfs(nums):\n\tif len(nums) <= 2:\n\t\treturn 1\n\tleft = [x in nums which < nums[0]]\n\tright = [x in nums which > nums[0]]\n\treturn combination(len(lefft+right), len(left)) * dfs(left) * dfs(right)\n```\nHere comes the tricky part for Java, doing mathematical stuff in Java is really a PAIN in the ass since it doesn\'t have ```comb()``` function in python and it doesn\'t support ```long long```, I didn\'t know why the hint is dynamic programming, now I get it, I can use Yang Hui/Pascal\'s triangle to speed up calculation and get rid of overflow, are you serious leetcode? \n```\nclass Solution {\n private static final long MOD = 1000000007;\n public int numOfWays(int[] nums) {\n int len = nums.length;\n List<Integer> arr = new ArrayList<>();\n for (int n : nums) {\n arr.add(n);\n }\n return (int)getCombs(arr, getTriangle(len + 1)) - 1;\n }\n \n private long getCombs(List<Integer> nums, long[][] combs) {\n if (nums.size() <= 2) {\n return 1;\n }\n int root = nums.get(0);\n List<Integer> left = new ArrayList<>();\n List<Integer> right = new ArrayList<>();\n for (int n : nums) {\n if (n < root) {\n left.add(n);\n } else if (n > root) {\n right.add(n);\n }\n }\n // mod every number to avoid overflow\n return (combs[left.size() + right.size()][left.size()] * (getCombs(left, combs) % MOD) % MOD) * getCombs(right, combs) % MOD;\n }\n \n private long[][] getTriangle(int n) {\n // Yang Hui (Pascle) triangle\n // 4C2 = triangle[4][2] = 6\n long[][] triangle = new long[n][n];\n for (int i = 0; i < n; i++) {\n triangle[i][0] = triangle[i][i] = 1;\n }\n for (int i = 2; i < n; i++) {\n for (int j = 1; j < i; j++) {\n triangle[i][j] = (triangle[i - 1][j] + triangle[i - 1][j - 1]) % MOD;\n }\n }\n return triangle;\n }\n}\n``` | 56 | 0 | [] | 6 |
number-of-ways-to-reorder-array-to-get-same-bst | C++/Python. Question explained. Then detailed solution. Short. Fast. Readable. | cpython-question-explained-then-detailed-659a | Question can seem confusing. Note that we are inserting the numbers in the binary search tree in exactly the same order as they occur in the input array. \n\nTh | axat-priy | NORMAL | 2020-08-30T08:57:57.183923+00:00 | 2020-08-31T01:50:08.760819+00:00 | 7,122 | false | Question can seem confusing. Note that we are inserting the numbers in the binary search tree in *exactly the same order as they occur in the input array*. \n\nThis is a good time to recall a fact which may seem very obvious but is crucial to understand the question: *For a fixed sequence of insertion, the number of binary search trees generated is exactly one.*\n\n### Approach\n\nKey insight: as long as the root of the binary search tree is inserted first (and recursively, other parents are inserted before their subtrees), any permutation of other elements will generate the same BST. This may feel a bit mouthful, so let\'s understand with an example.\n\nFor BST given in example, as long as 3 comes before others, 4 comes before 5, 1 comes before 2, we can generate the same BST.\n\n\nThis is true for all of the following arrays:\n```python\n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]\n```\nLet\'s see an example of [3, 4, 1, 5, 2]\n\nFirst to insert is 3. Tree is just a single node 3.\n\nThen we insert 4. Has to go on right of 3. Tree is\n```\n 3\n\t \\\n\t 4\n```\n\nThen we insert 1. (Again note that we have to insert in the same order as input array. I\'ll repeat this several times :D)\n\n```\n 3\n\t / \\\n\t1 4\n```\n\nThen 5\n```\n 3\n\t / \\\n\t1 4\n\t \\\n\t\t 5\n```\n\nThen 2\n\n```\n 3\n\t / \\\n\t1 4\n \t \\ \\\n\t 2\t 5\n```\n\nTry other arrays listed above and convince yourself that it will generate identical BST.\n\nSo, for this BST, \n\n- choose 3 as root (the element which is first in insertion order)\n- `[1,2]` will be in the `left` subtree. Maintaining order is important to ensure that we generate the same BST. Let `m = left.size()`\n- `[4,5]` in `right` subtree. Let `n = right.size()`\n- find ways to interleave them.\nThe number of ways are just interleavings of left and right. Similar to https://leetcode.com/problems/interleaving-string/\nHow many ways are there to interleave left and right?\n\nThere are `m + n` total positions. If we put `m` elements from `left` in randomly chosen `m` positions (but, in order), we can put the rest in other (right ;-)) positions. (Equivalently, we could also have chosen to fill `n` arbitrary positions from `right` and fill remaining from whatever positions are left.)\n\nThat\u2019s just:\n\n\n\nSo algorithm would be\n\n- Fix the root (first element of the input)\n- Find smaller and larger elements than root. These would be left and right subtrees (meh)\n- Combine, which is an interleaving as explained above.\n\nFollow up: If you actually want to [generate all the arrays](https://stackoverflow.com/questions/21211701/given-a-bst-and-its-root-print-all-sequences-of-nodes-which-give-rise-to-the-sa/24398114#24398114)\n\n### Python\n```python\nclass Solution:\n\n def numOfWays(self, numbers):\n mod = 10 ** 9 + 7\n\n def ways_to_interleave(sequence_1, sequence_2):\n """\n Number of ways to interleave two sequences (i.e. maintaining the order)\n """\n total_things = len(sequence_1) + len(sequence_2)\n things_to_choose = len(sequence_1) # or len(sequence_2), doesn\'t matter.\n return math.comb(total_things, things_to_choose)\n\n def helper(subsequence):\n if not subsequence:\n return 1\n root_value = subsequence[0]\n left = [number for number in subsequence if number < root_value]\n right = [number for number in subsequence if number > root_value]\n ways_to_arrange_left = helper(left)\n ways_to_arrange_right = helper(right)\n return ways_to_arrange_left * ways_to_arrange_right * ways_to_interleave(left, right)\n return (helper(numbers) - 1) % mod\n\n```\nThis surprisingly beats all other python solutions so far (but speed is not the aim of this code, it\'s readability)\n\n### C++\n\nPeople who build numerical libraries have my huge respect. Getting [`combinations` method (ommitted) without overflow is tricky for a C++ noob like me. I\'ve lifted the version from here](https://stackoverflow.com/questions/11809502/which-is-better-way-to-calculate-ncr?noredirect=1&lq=1). Others have used pascal triangle methods, which are easiest to implement in interview and worth a look.\n\n```cpp\n#include <vector>\n#include <cmath>\n#include <algorithm>\n\nclass Solution {\npublic:\n int numOfWays(std::vector<int>& numbers) {\n\t\t\treturn (helper(numbers) - 1) % mod;\n }\n\nprivate:\n\t\tint mod = std::pow(10, 9) + 7;\n\n\t\tint ways_to_interleave(int sequence_1_length, int sequence_2_length) {\n\t\t\treturn combinations(sequence_1_length + sequence_2_length, sequence_2_length, mod); // combinations function is omitted as it\'s not really relevant to core issue of the question.\n\t\t}\n\n\t\tlong helper(const std::vector<int>& numbers) {\n\t\t\tif (numbers.empty()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tint root_value = numbers[0];\n\t\t\tstd::vector<int> left, right;\n\t\t\tstd::copy_if(numbers.begin(), numbers.end(), std::back_inserter(left), [root_value](int number){return number < root_value;});\n\t\t\tstd::copy_if(numbers.begin(), numbers.end(), std::back_inserter(right), [root_value](int number){return number > root_value;});\n\t\t\tlong ways_to_arrange_left = helper(left) % mod;\n\t\t\tlong ways_to_arrange_right = helper(right) % mod;\n long duck_this = (ways_to_arrange_left * ways_to_arrange_right) % mod;\n\t\t\tlong duck_this_too = (duck_this * ways_to_interleave(left.size(), right.size())) % mod;\n return duck_this_too;\n\t\t\t\t\t}\n};\n``` | 55 | 2 | ['C', 'Python'] | 4 |
number-of-ways-to-reorder-array-to-get-same-bst | [ BST ]β
|| Hard to Easyπ₯ || C++β, Javaπ & Python Clear βοΈ | bst-hard-to-easy-c-java-python-clear-by-pqq9s | Intuition\n- To construct a BST, we need to select a root node and divide the remaining elements into two groups: the left subtree (containing elements smaller | iamsanko | NORMAL | 2023-06-16T03:24:01.608432+00:00 | 2023-06-20T02:14:02.415909+00:00 | 8,080 | false | # Intuition\n- To construct a BST, we need to select a root node and divide the remaining elements into two groups: the left subtree (containing elements smaller than the root) and the right subtree (containing elements larger than the root). The order of elements within each subtree doesn\'t matter as long as the relative order of the elements with respect to the root is maintained.\n\n- Based on this observation, we can approach the problem recursively. For a given array nums, we can select the first element as the root and divide the remaining elements into the left and right subtrees. Then, we recursively count the number of BSTs for the left and right subtrees and multiply them by the number of possible combinations of left and right subtrees. The total count is the product of these values.\n\n---\n# Kindly Vote Sir Please \n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. The problem requires counting the number of ways to reorder the given array such that the resulting order yields the same binary search tree (BST). To solve the problem, we can use a recursive approach combined with the concept of Catalan numbers.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n# Time complexity: O(N^3).\nThe time complexity of the solution is determined by the number of recursive calls made to the countBST function. In the worst case, the recursive function will be called for every possible division of the array into left and right subtrees. Since each recursive call reduces the size of the array by one, the number of recursive calls is proportional to the number of elements in the array, which is O(N). Additionally, calculating the binomial coefficients using dynamic programming takes O(N^2) time. Therefore, the overall time complexity is O(N^3).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n# Space complexity: O(N^2)\nThe space complexity is determined by the recursion stack used for the recursive calls. In the worst case, the recursion depth can be equal to the number of elements in the array, which is O(N). Additionally, the dynamic programming approach for calculating binomial coefficients requires O(N^2) space for the 2D dp array. Therefore, the overall space complexity is O(N^2).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n# Note \nThe space complexity can be further optimized by using memoization techniques to avoid redundant calculations of binomial coefficients. This can be achieved by storing previously computed values in a memoization table. With memoization, the space complexity can be reduced to O(N) for both time and space.\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) {\n const int MOD = 1e9 + 7;\n return (countBST(nums) - 1 + MOD) % MOD; // Subtract 1 to exclude the original ordering\n }\n\nprivate:\n int countBST(vector<int>& nums) {\n if (nums.size() <= 2)\n return 1;\n\n vector<int> left, right;\n int root = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] < root)\n left.push_back(nums[i]);\n else\n right.push_back(nums[i]);\n }\n\n long long leftCount = countBST(left); // Count the number of BSTs for the left subtree\n long long rightCount = countBST(right); // Count the number of BSTs for the right subtree\n\n // Calculate the number of combinations using the Catalan number formula\n long long totalCount = binomialCoefficient(left.size() + right.size(), left.size());\n\n return (leftCount * rightCount % 1000000007 * totalCount % 1000000007);\n }\n\n long long binomialCoefficient(int n, int k) {\n const int MOD = 1e9 + 7;\n\n vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, 0));\n dp[0][0] = 1;\n\n for (int i = 1; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= min(i, k); j++) {\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD;\n }\n }\n\n return dp[n][k];\n }\n};\n\n```\n```Java []\n\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) {\n const int MOD = 1e9 + 7;\n return (countBST(nums) - 1 + MOD) % MOD; // Subtract 1 to exclude the original ordering\n }\n\nprivate:\n int countBST(vector<int>& nums) {\n if (nums.size() <= 2)\n return 1;\n\n vector<int> left, right;\n int root = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] < root)\n left.push_back(nums[i]);\n else\n right.push_back(nums[i]);\n }\n\n long long leftCount = countBST(left); // Count the number of BSTs for the left subtree\n long long rightCount = countBST(right); // Count the number of BSTs for the right subtree\n\n // Calculate the number of combinations using the Catalan number formula\n long long totalCount = binomialCoefficient(left.size() + right.size(), left.size());\n\n return (leftCount * rightCount % 1000000007 * totalCount % 1000000007);\n }\n\n long long binomialCoefficient(int n, int k) {\n const int MOD = 1e9 + 7;\n\n vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, 0));\n dp[0][0] = 1;\n\n for (int i = 1; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= min(i, k); j++) {\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD;\n }\n }\n\n return dp[n][k];\n }\n};\n\n```\n```Python []\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n return (self.countBST(nums) - 1 + MOD) % MOD\n\n def countBST(self, nums: List[int]) -> int:\n if len(nums) <= 2:\n return 1\n\n left = []\n right = []\n root = nums[0]\n\n for i in range(1, len(nums)):\n if nums[i] < root:\n left.append(nums[i])\n else:\n right.append(nums[i])\n\n leftCount = self.countBST(left)\n rightCount = self.countBST(right)\n\n totalCount = self.binomialCoefficient(len(left) + len(right), len(left))\n\n return (leftCount * rightCount * totalCount) % MOD\n\n def binomialCoefficient(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n dp[0][0] = 1\n\n for i in range(1, n + 1):\n dp[i][0] = 1\n for j in range(1, min(i, k) + 1):\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD\n\n return dp[n][k]\n\n```\n | 30 | 0 | ['Divide and Conquer', 'Dynamic Programming', 'C++'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ DFS + Comb | c-dfs-comb-by-votrubac-9bct | cpp\nint dp[1001][1001] = {};\nint comb(int n, int m) {\n return n == 0 || m == 0 ? 1 :\n dp[n][m] ? dp[n][m] : \n dp[n][m] = (comb(n - 1, | votrubac | NORMAL | 2020-09-01T00:44:37.037364+00:00 | 2020-09-01T00:45:26.669317+00:00 | 4,886 | false | ```cpp\nint dp[1001][1001] = {};\nint comb(int n, int m) {\n return n == 0 || m == 0 ? 1 :\n dp[n][m] ? dp[n][m] : \n dp[n][m] = (comb(n - 1, m) + comb(n, m - 1)) % 1000000007;\n}\nlong dfs(vector<int>& n) {\n if (n.size() <= 1)\n return 1;\n vector<int> n1, n2;\n copy_if(begin(n), end(n), back_inserter(n1), [&] (int i) { return i < n.front(); });\n copy_if(begin(n), end(n), back_inserter(n2), [&] (int i) { return i > n.front(); });\n return dfs(n1) * dfs(n2) % 1000000007 * comb(n1.size(), n2.size()) % 1000000007;\n}\nint numOfWays(vector<int>& n) { return dfs(n) - 1; }\n``` | 27 | 8 | [] | 5 |
number-of-ways-to-reorder-array-to-get-same-bst | [Python] O(n^2) post-order traversal | python-on2-post-order-traversal-by-yanru-ip0h | Idea\nThe key idea is to maintain the topological order of the BST. \nMore specifically, this solution works in this way. \n\nStep 1\nFor every node, given that | yanrucheng | NORMAL | 2020-08-30T04:01:13.907314+00:00 | 2020-08-30T04:12:01.611862+00:00 | 2,942 | false | ## Idea\nThe key idea is to maintain the topological order of the BST. \nMore specifically, this solution works in this way. \n\n**Step 1**\nFor every node, given that its left subtree has `L` children and its right subtree has `R` children. We denote the number of way to schedule the placement of `L + R` nodes as `N(L, R)`. We then have the following relation.\n- `N(L, R) = N(L - 1, R) + N(L, R - 1)`, if we want to place 2 subtrees simultaneously, we can place one element either from the left, or from the right.\n- `N(L, 0) = 1` and `N(0, R) = 1`, if we only have one subtree to place, we have only 1 option, that is to place this subtree directly.\n\n**Step 2**\nWe then compute the product of all `N` values for all the nodes.\n\nPlease leave an upvote if you like my post. It means a lot to me.\n\n## Complexity\n- Time and Space: `O(n^2)`\n\n## Python\n```\nfrom functools import lru_cache\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n @lru_cache(None)\n def combine(x, y):\n if x == 0 or y == 0: return 1\n return combine(x, y - 1) + combine(x - 1, y)\n \n bst = TreeNode(nums[0])\n for n in nums[1:]:\n bst.add(n)\n \n res = 1\n def traverse(root):\n nonlocal res\n if not root: return 0\n lc = traverse(root.left)\n rc = traverse(root.right)\n res = res * combine(lc, rc) % 1000000007\n return lc + rc + 1\n traverse(bst)\n \n return res - 1\n \nclass TreeNode:\n def __init__(self, v):\n self.val = v\n self.left = None\n self.right = None\n \n def add(self, v): \n curr = self\n node = TreeNode(v)\n while 1:\n if v < curr.val:\n if not curr.left:\n curr.left = node\n break\n curr = curr.left\n else: \n if not curr.right:\n curr.right = node\n break\n curr = curr.right\n``` | 27 | 3 | [] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | O(N) simple&fast | on-simplefast-by-617280219-tchx | First, the answer can be expressed as n!/Product(size(i),i=1..n)-1, where size(i) denotes the size of subtree with root i.\nThen we have some observations:\n1. | 617280219 | NORMAL | 2020-09-10T08:25:12.704430+00:00 | 2020-09-10T08:26:26.169909+00:00 | 3,105 | false | First, the answer can be expressed as n!/Product(size(i),i=1..n)-1, where size(i) denotes the size of subtree with root i.\nThen we have some observations:\n1. any node in subtree must be inserted after the root\n2. any subtree contains a consecutive interval\n3. after any insertion step, any remaining interval will finally form a subtree\n\nNow if we invert the insertion process, it becomes deleting nodes from a BST. The observations\n1. the root of a subtree is the last deleted node in that subtree\n2. any deleted subtree contains a consecutive interval\n3. after any deletion step, any removed interval form a subtree\n\nWhen a node p is deleted, both of its subtree are already deleted. And if p+1(or p-1) is deleted, it must belong to the right(or left) subtree of p. Otherwise their LCA is not deleted yet and must have value between them, which is impossible. So the deleted interval that contains p+1(or p-1) just forms the right(or left) subtree of p. Adding p to the set of deleted nodes will possibly connect two intervals or extend one interval, which corresponds to the two subtrees of p being non-empty or only one subtree being non-empty. Therefore, using a doubly linked list, we can easily merge intervals and calculate their length, which is the size of subtrees.\nTake [3,4,5,1,2] as an example:\nStep 0. complete BST, no deleted nodes yet\nThe doubly linked list is like 1--2--3--4--5\nStep 1. delete 2\nNow we know that the subtree with root 2 has size 1. The node itself form an interval.\nThe doubly linked list is now 1--[2,2]--3--4--5\nStep 2. delete 1\nWe find that 2 is already deleted, so we extend the deleted interval. Now we know that the subtree with root 1 has size 2. The two nodes form an interval.\nThe doubly linked list is now [1,2]--3--4--5\nStep 3. delete 5\nNow we know that the subtree with root 5 has size 1.\nThe doubly linked list is now [1,2]--3--4--[5,5]\nStep 4. delete 4\nNow we know that the subtree with root 4 has size 2.\nThe doubly linked list is now [1,2]--3--[4,5]\nStep 5. delete 3\nNote that both 2 and 4 are deleted, so we connect the two intervals with 3, and find that the subtree with root 3 has size 5.\nThe doubly linked list is now [1,5].\nNow we calculate the answer: 5!/(1x2x1x2x5)-1=5.\nThe inverse element of 1..n under modulo can be calculated in O(n), and there are n operations in doubly linked list each with O(1) time cost, so the overall time complexity is O(n).\n```\n#define MOD 1000000007\n\nclass Node {\npublic:\n int size,flag;\n Node *l,*r;\n Node(int s=1,Node* a=NULL,Node* b=NULL):size(s),flag(0),l(a),r(b){}\n};\n\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) {\n int n=nums.size();\n int inv[n+1];inv[1]=1;\n long long s=1;\n for(int i=2;i<=n;i++)\n {\n inv[i]=((long long)(MOD-MOD/i)*inv[MOD%i])%MOD;\n s=(s*i)%MOD;\n }\n Node p[n+2];\n for(int i=0;i<=n+1;i++)\n {\n p[i].l=p+i-1;\n p[i].r=p+i+1;\n }\n for(auto it=nums.rbegin();it<nums.rend();it++)\n {\n Node& t=p[*it];t.flag=1;\n if(t.l->flag){t.l->l->r=&t;t.size+=t.l->size;t.l=t.l->l;}\n if(t.r->flag){t.r->r->l=&t;t.size+=t.r->size;t.r=t.r->r;}\n if(t.size>1)s=(s*inv[t.size])%MOD;\n }\n return (s+MOD-1)%MOD;\n }\n};\n``` | 23 | 0 | [] | 5 |
number-of-ways-to-reorder-array-to-get-same-bst | Java Solution for Number of Ways to Reorder Array to Get Same BST Problem | java-solution-for-number-of-ways-to-reor-hfb4 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem asks for the number of different ways to reorder the given array nums such | Aman_Raj_Sinha | NORMAL | 2023-06-16T03:24:12.256675+00:00 | 2023-06-16T03:24:12.256692+00:00 | 7,226 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks for the number of different ways to reorder the given array nums such that the constructed Binary Search Tree (BST) is identical to the original BST formed from nums. We can solve this problem recursively by considering the root element of the BST and splitting the remaining elements into two groups: the left subtree elements (less than the root) and the right subtree elements (greater than the root). The total number of ways to reorder nums can be calculated by multiplying the number of ways to reorder the left subtree, the number of ways to reorder the right subtree, and the number of possible combinations of left and right subtrees.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a helper function countWays that takes a list of integers (nums) as input and returns the number of ways to reorder nums to form the same BST.\n1. In the countWays function:\n- If the size of nums is less than or equal to 2, return 1 since there is only one way to reorder 0 or 1 element.\n- Create two empty lists: left and right.\n- Set the first element of nums as the root value.\n- Iterate through the remaining elements of nums (starting from the second element):\n- If the current element is less than the root value, add it to the left list.\n- Otherwise, add it to the right list.\n- Calculate the number of ways to reorder the left list (recursively) and store it in leftCount.\n- Calculate the number of ways to reorder the right list (recursively) and store it in rightCount.\n- Calculate the number of possible combinations of left and right subtrees using the comb function.\n- Return the product of comb, leftCount, and rightCount.\n3. Create a numOfWays function that converts the input array into a list and calls the countWays function. Subtract 1 from the result and return it as the final output.\n1. Test the program with provided test cases or additional test cases.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the solution is O(n^2), where n is the size of the nums array. This is because for each recursive call, we split the list into left and right subtrees, and in the worst case, the number of elements in the subtrees can be O(n). The comb function also has a time complexity of O(n^2) because it calculates combinations using dynamic programming.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) because we use additional space to store the left and right subtrees. The depth of the recursion can be at most n, so the space required for recursion is also O(n).\n\n# Code\n```\nclass Solution {\n private static final int MOD = 1000000007;\n public int numOfWays(int[] nums) {\n List<Integer> list = new ArrayList<>();\n for (int num : nums) {\n list.add(num);\n }\n return countWays(list) - 1;\n }\n private int countWays(List<Integer> nums) {\n if (nums.size() <= 2) {\n return 1;\n }\n \n List<Integer> left = new ArrayList<>();\n List<Integer> right = new ArrayList<>();\n int root = nums.get(0);\n \n for (int i = 1; i < nums.size(); i++) {\n if (nums.get(i) < root) {\n left.add(nums.get(i));\n } else {\n right.add(nums.get(i));\n }\n }\n \n long leftCount = countWays(left);\n long rightCount = countWays(right);\n \n return (int) ((comb(nums.size() - 1, left.size()) % MOD) * (leftCount % MOD) % MOD * (rightCount % MOD) % MOD);\n }\n \n private long comb(int n, int k) {\n long[][] dp = new long[n + 1][k + 1];\n for (int i = 0; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= Math.min(i, k); j++) {\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD;\n }\n }\n return dp[n][k];\n }\n}\n``` | 20 | 0 | ['Java'] | 4 |
number-of-ways-to-reorder-array-to-get-same-bst | 2 Easiest C++ Solutionπ₯ || DPπ₯ || Fastest π₯π₯π₯ | 2-easiest-c-solution-dp-fastest-by-black-xr3q | \n# Approach : Dynamic Programming\n Describe your approach to solving the problem. \n\n# Code 1\n\nclass Solution {\n vector<vector<long long int>> dp;\n | Black_Mamba01 | NORMAL | 2023-06-16T01:25:00.542460+00:00 | 2023-06-16T18:15:22.010699+00:00 | 16,481 | false | \n# Approach : Dynamic Programming\n<!-- Describe your approach to solving the problem. -->\n\n# Code 1\n```\nclass Solution {\n vector<vector<long long int>> dp;\n long long MOD = 1e9 + 7;\n\n unsigned long long solve(vector<int> &nums) {\n if (nums.size() <= 1) return 1;\n vector<int> l, r;\n for (int i = 1; i < nums.size(); ++i) {\n if (nums[i] > nums[0]) r.push_back(nums[i]);\n else l.push_back(nums[i]);\n }\n int n = l.size(), m = r.size();\n return solve(l) * solve(r) % MOD * dp[n + m][n] % MOD;\n }\n\npublic:\n int numOfWays(vector<int> &nums) {\n dp = vector<vector<long long>>(nums.size() + 1, vector<long long>(nums.size() + 1, 0));\n for (int i = 1; i < nums.size() + 1; ++i) {\n dp[i][0] = 1;\n dp[i][1] = i;\n dp[i][i - 1] = i;\n dp[i][i] = 1;\n }\n for (int i = 2; i < nums.size() + 1; ++i) {\n for (int j = 2; j < nums.size() + 1; ++j) {\n if (i >= j) dp[i][j] = (dp[i - 1][j - 1] % MOD + dp[i - 1][j] % MOD) % MOD;\n else break;\n }\n }\n return solve(nums) - 1;\n }\n};\n```\n\n\n# Approach : Pascal Triangle\n<!-- Describe your approach to solving the problem. -->\n\n# Code 2\n```\nclass Solution {\npublic:\n vector < vector < long long > > pascal;\n int MOD = 1e9 + 7;\n \n int numOfWays(vector<int>& nums) {\n int N = nums.size();\n pascal = vector < vector < long long > > (N + 1);\n for (int i = 0; i < N + 1; i ++){\n pascal[i] = vector < long long > (i + 1, 1);\n for (int j = 1; j < i; j ++){\n pascal[i][j] = (pascal[i - 1][j] + pascal[i - 1][j - 1])%MOD;\n }\n }\n return dfs(nums) - 1;\n }\n \n int dfs(vector < int > nums){\n if (nums.size() <= 2)\n return 1;\n vector < int > left, right;\n for (int i = 1; i < int(nums.size()); i ++){\n if (nums[i] < nums[0])\n left.push_back(nums[i]);\n else\n right.push_back(nums[i]);\n }\n return (((dfs(left) * pascal[nums.size() - 1][left.size()]) % MOD) * dfs(right))%MOD;\n }\n};\n``` | 19 | 0 | ['Divide and Conquer', 'Dynamic Programming', 'Combinatorics', 'C++'] | 4 |
number-of-ways-to-reorder-array-to-get-same-bst | πC++ || Recursion || (IMP nCr) | c-recursion-imp-ncr-by-chiikuu-ty7c | Code\n\nclass Solution {\npublic:\n vector<vector<long long>>ncr;\n long long mod=1e9+7;\n long long ways(vector<int>&v,int n){\n if(n<=2)return | CHIIKUU | NORMAL | 2023-06-16T05:46:08.282451+00:00 | 2023-06-16T05:46:08.282483+00:00 | 4,351 | false | # Code\n```\nclass Solution {\npublic:\n vector<vector<long long>>ncr;\n long long mod=1e9+7;\n long long ways(vector<int>&v,int n){\n if(n<=2)return 1;\n vector<int>left,right;\n for(int i=1;i<n;i++){\n if(v[0]>v[i])left.push_back(v[i]);\n else right.push_back(v[i]);\n }\n long long ans_left=ways(left,left.size());\n long long ans_right=ways(right,right.size());\n\n long long ans = (((ncr[n-1][left.size()]*ans_left)%mod)*ans_right)%mod;\n return ans;\n }\n int numOfWays(vector<int>& v) {\n int n=v.size();\n ncr.resize(n + 1);\n for(int i = 0; i < n + 1; ++i){\n ncr[i] = vector<long long>(i + 1, 1);\n for(int j = 1; j < i; ++j){\n ncr[i][j] = (ncr[i-1][j-1] + ncr[i-1][j]) % mod;\n }\n }\n \n return (ways(v,n)-1)%mod;\n }\n};\n```\n\n | 17 | 0 | ['Math', 'Tree', 'Recursion', 'Combinatorics', 'C++'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | Didn't see any Java solution here, because nobody knows how to mod? | didnt-see-any-java-solution-here-because-okfn | Sadly me neither\n```\nclass Solution {\n long mod = (int) 1e9 + 7;\n public int numOfWays(int[] nums) {\n List list = new LinkedList<>();\n | JulesX01 | NORMAL | 2020-08-30T04:24:44.000623+00:00 | 2020-08-30T04:24:44.000655+00:00 | 2,290 | false | Sadly me neither\n```\nclass Solution {\n long mod = (int) 1e9 + 7;\n public int numOfWays(int[] nums) {\n List<Integer> list = new LinkedList<>();\n for(int i:nums){\n list.add(i);\n }\n\n return (int)(((helper(list)-1)%mod) % mod);\n }\n \n private long helper(List<Integer> list){\n if(list.size() == 0 || list.size() == 1) return 1;\n \n int root = list.get(0);\n List<Integer> bigger = new LinkedList<>();\n List<Integer> smaller = new LinkedList<>();\n\n for(int i:list){\n if(i > root){\n bigger.add(i);\n }\n if(i < root){\n smaller.add(i);\n }\n }\n int n = list.size();\n int left = smaller.size();\n long temp = (fac(n-1) / (fac(left)));\n temp = temp/fac(n-1-left);\n \n return (temp * helper(smaller) * helper(bigger));\n }\n \n private long fac(int n){\n long res = 1;\n while(n > 1){\n res = res * n;\n n--;\n }\n return res;\n }\n} | 17 | 1 | [] | 8 |
number-of-ways-to-reorder-array-to-get-same-bst | JavaScript | With Comments and Explanation [100%, 100%] (Combination + Mathematics) | javascript-with-comments-and-explanation-fcgp | Approach\nFind the number of ways to sort a list by replacing two elements at a time in given array\n\nPlease upvote me if you like this solution\n\n\n# Code\n\ | JayPokale | NORMAL | 2023-06-16T03:38:00.436970+00:00 | 2023-06-16T04:26:05.209771+00:00 | 1,357 | false | # Approach\nFind the number of ways to sort a list by replacing two elements at a time in given array\n```\nPlease upvote me if you like this solution\n```\n\n# Code\n```\n// Main Function\nvar numOfWays = function(nums) {\n return (helper(nums) - 1n) % BigInt(1e9+7) // Return modulo value\n};\n\n// Function return combination (Mathematics) [Formula = n!/( k!*(n-k)!)]\nvar nCr = (n,r) => {\n if(n < 2) return 1n;\n n = BigInt(n), r = BigInt(r);\n return fact(n) / (fact(n-r) * fact(r));\n}\n\nconst cache = new Map(); // Chache for factorials\n// Returns factorial of n [Formula = n!]\nvar fact = (n) => {\n if(n < 2) return 1n;\n if(cache.has(n)) return cache.get(n);\n const res = BigInt(n) * fact(n - 1n);\n cache.set(n, res);\n return res;\n}\n\nvar helper = (nums) => {\n if(nums.length < 3) return 1n;\n\n const left = [], right = []\n // Separate lower and higher values than first element in nums\n for(let i=1; i<nums.length; ++i) {\n if(nums[i] < nums[0]) left.push(nums[i])\n if(nums[i] > nums[0]) right.push(nums[i])\n }\n\n // Number of possible combinations to get left and right separated\n const comb = nCr(nums.length-1, left.length)\n return comb * helper(left) * helper(right);\n}\n``` | 16 | 1 | ['JavaScript'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Simple (divide and conquer) Python solution with explanation | simple-divide-and-conquer-python-solutio-15d3 | Consider example 2 in the problem:Observations
The first number cannot be rearranged because moving it will change the root of the tree.
Swapping any numbers be | cthlo | NORMAL | 2021-06-08T07:31:28.392859+00:00 | 2025-01-20T23:11:45.109589+00:00 | 1,668 | false | Consider example 2 in the problem:

```
Input: nums = [3,4,5,1,2]
Output: 5
Explanation: The following 5 arrays will yield the same BST:
[3,1,2,4,5]
[3,1,4,2,5]
[3,1,4,5,2]
[3,4,1,2,5]
[3,4,1,5,2]
```
### Observations
1. The first number cannot be rearranged because moving it will change the root of the tree.
2. Swapping any numbers between left and right subarrays will yield the same tree.
### Key
Focus on observation #2:
- The left subarray is `[1,2]` (all numbers after the root (`3`) that are smaller than the root)
- The right subarray is `[4,5]` (all numbers after the root (`3`) that are larger than the root)
How many ways can we merge these 2 subarrays while keeping the order within each subarray?
```
L: 1 2
R: 4 5 => [1,2,4,5]
-----------------------------------------------
L: 1 2
R: 4 5 => [1,4,2,5]
-----------------------------------------------
L: 1 2
R: 4 5 => [4,1,2,5]
-----------------------------------------------
...
```
The number of ways to "interleave" the 2 arrays is `{len(L) + len(R)} choose {len(L)}` (or, `{len(L) + len(R)} choose {len(R)}`), i.e. `(2+2) choose (2) = 6` ways. (You can think of it as number of ways to put 2 identical items in 4 slots)
We know that (from observation #2) these rearrangements of the numbers after the root (`3`) will yield the same tree.
What this means is, if we know the numbers of permutations (`numOfWays`) of the left and right subarrays, then we can calculate the overall permutations for the current tree:
```
choose(len(left_subarray)+len(right_subarray), len(left_subarray)) # (call this K)
X
numOfWays(left_subarray)
X
numOfWays(right_subarray)
```
because for each arrangement pair of the left and right subarrays, there are `K` ways to merge them.
So, we can recursively compute the permutations in each subtree/subarray, and then calculate the overall permutations based on the above formula.
### Divide and conquer
```python
import operator as op
from functools import reduce
def choose(n, r):
"""https://stackoverflow.com/a/4941932
"""
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom
class Solution:
def numOfWays(self, nums: List[int]) -> int:
def divideAndConquer(sublist):
if len(sublist) <= 1: # base case
return 1
root = sublist[0]
left = [n for n in sublist if n < root] # left subarray
right = [n for n in sublist if n > root] # right subarray
leftWays = divideAndConquer(left)
rightWays = divideAndConquer(right)
return choose(len(left)+len(right), len(left)) * leftWays * rightWays
# minus 1 because the answer needs to exclude the input
return (divideAndConquer(nums) - 1) % 1000000007
``` | 14 | 0 | ['Divide and Conquer', 'Python'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Video Solution | Java C++ Python | video-solution-java-c-python-by-jeevanku-8vm8 | \n\n\n\n\n\n\n\n\nclass Solution {\n long mod = (long)1e9 + 7;\n long[][] table;\n public int numOfWays(int[] nums) {\n int n = nums.length;\n | jeevankumar159 | NORMAL | 2023-06-16T04:49:09.497491+00:00 | 2023-06-16T04:49:41.612248+00:00 | 2,004 | false | \n\n\n\n<iframe width="560" height="315" src="https://www.youtube.com/embed/N8MDBYhF4dM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n\n\n```\nclass Solution {\n long mod = (long)1e9 + 7;\n long[][] table;\n public int numOfWays(int[] nums) {\n int n = nums.length;\n table = new long[n][n];\n for (int i = 0; i < n; ++i) {\n table[i][0] = table[i][i] = 1;\n }\n for (int i = 2; i < n; i++) {\n for (int j = 1; j < i; j++) {\n table[i][j] = (table[i - 1][j - 1] + table[i - 1][j]) % mod;\n }\n }\n List<Integer> arrList = new ArrayList();\n for(int i: nums) arrList.add(i);\n return (int)((helper(arrList) - 1) % mod);\n \n }\n \n public long helper(List<Integer> arr){\n int n = arr.size();\n if(n<3) return 1;\n List<Integer> leftNodes = new ArrayList<>();\n List<Integer> rightNodes = new ArrayList<>();\n for (int i = 1; i<n;i++) {\n int element = arr.get(i);\n if (element < arr.get(0)) {\n leftNodes.add(element);\n } else {\n rightNodes.add(element);\n }\n }\n long leftWays = helper(leftNodes)%mod;\n long rightWays = helper(rightNodes) % mod;\n return (((leftWays * rightWays) % mod) * table[n - 1][leftNodes.size()]) % mod;\n }\n}\n```\n\n```\n\n\nclass Solution {\n long long mod = 1000000007;\n std::vector<std::vector<long long>> table;\n \npublic:\n int numOfWays(std::vector<int>& nums) {\n int n = nums.size();\n table.resize(n, std::vector<long long>(n));\n \n for (int i = 0; i < n; ++i) {\n table[i][0] = table[i][i] = 1;\n }\n \n for (int i = 2; i < n; i++) {\n for (int j = 1; j < i; j++) {\n table[i][j] = (table[i - 1][j - 1] + table[i - 1][j]) % mod;\n }\n }\n \n std::vector<int> arrList;\n for (int i : nums)\n arrList.push_back(i);\n \n return (int)((helper(arrList) - 1) % mod);\n }\n \n long long helper(std::vector<int>& arr) {\n int n = arr.size();\n if (n < 3)\n return 1;\n \n std::vector<int> leftNodes;\n std::vector<int> rightNodes;\n \n for (int i = 1; i < n; i++) {\n int element = arr[i];\n if (element < arr[0]) {\n leftNodes.push_back(element);\n } else {\n rightNodes.push_back(element);\n }\n }\n \n long long leftWays = helper(leftNodes) % mod;\n long long rightWays = helper(rightNodes) % mod;\n \n return (((leftWays * rightWays) % mod) * table[n - 1][leftNodes.size()]) % mod;\n }\n};\n\n```\n\n```\nclass Solution:\n mod = 10**9 + 7\n table = []\n\n def numOfWays(self, nums):\n n = len(nums)\n self.table = [[0] * n for _ in range(n)]\n\n for i in range(n):\n self.table[i][0] = self.table[i][i] = 1\n\n for i in range(2, n):\n for j in range(1, i):\n self.table[i][j] = (self.table[i - 1][j - 1] + self.table[i - 1][j]) % self.mod\n\n arrList = nums\n return (self.helper(arrList) - 1) % self.mod\n\n def helper(self, arr):\n n = len(arr)\n if n < 3:\n return 1\n\n leftNodes = []\n rightNodes = []\n for i in range(1, n):\n element = arr[i]\n if element < arr[0]:\n leftNodes.append(element)\n else:\n rightNodes.append(element)\n\n leftWays = self.helper(leftNodes) % self.mod\n rightWays = self.helper(rightNodes) % self.mod\n\n return (((leftWays * rightWays) % self.mod) * self.table[n - 1][len(leftNodes)]) % self.mod\n\n``` | 12 | 0 | ['C', 'Python', 'Java'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | Java simple DFS | java-simple-dfs-by-hobiter-hig3 | 1, once root is fixed, find all following nums < root, list left, to form left subtree;\nfind all following nums >root, list right, to form left subtree;\n2, fi | hobiter | NORMAL | 2020-09-04T02:45:24.784580+00:00 | 2020-09-04T02:55:14.873038+00:00 | 1,527 | false | 1, once root is fixed, find all following nums < root, list<Integer> left, to form left subtree;\nfind all following nums >root, list<Integer> right, to form left subtree;\n2, find all combinations, comb, to select left.size() positions for left from all following positions after root, left.size() + right.size().\n3, result will be comb * dfs(left) * dfs(right);\n4, to calculate comb, you can either use [combination formula](https://www.mathplanet.com/education/algebra-2/discrete-mathematics-and-probability/permutations-and-combinations#:~:text=The%20number%20of%20combinations%20of,r!), or [Yang Hui Triangle](https://en.wikipedia.org/wiki/Yang_Hui) \n```\nclass Solution {\n long mod = 1_000_000_007, dp[][];\n public int numOfWays(int[] nums) {\n dp = getYang(nums.length);\n List<Integer> list = new ArrayList<>(); \n for (int n : nums) list.add(n);\n return (int) (dfs(list) - 1);\n }\n \n private long dfs(List<Integer> l) {\n if (l.size() < 3) return 1;\n int root = l.get(0);\n List<Integer> left = new ArrayList<>(), right = new ArrayList<>();\n for (int i = 1; i < l.size(); i++) {\n if (l.get(i) < root) left.add(l.get(i));\n else right.add(l.get(i));\n }\n return dp[left.size() + right.size()][left.size()] % mod * dfs(left) % mod * dfs(right) % mod;\n }\n \n private long[][] getYang(int n) {\n long[][] res = new long[n + 1][n + 1];\n for (int i = 1; i <= n; i++) res[i][0] = res[i][i] = 1;\n for (int i = 2; i <= n; i++) \n for (int j = 1; j < i; j++) \n res[i][j] = (res[i - 1][j] + res[i - 1][j - 1]) % mod; \n return res;\n }\n}\n``` | 12 | 1 | [] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | [Java] Accepted Java solution | java-accepted-java-solution-by-mcjiang-czf2 | Didn\'t really enjoy the puzzle, started with long data type and kept MOD\'ing whenever I can but still overflow. I thought it was my algorithm but switching to | mcjiang | NORMAL | 2020-08-30T04:39:29.047764+00:00 | 2020-08-30T04:50:06.795897+00:00 | 2,121 | false | Didn\'t really enjoy the puzzle, started with long data type and kept MOD\'ing whenever I can but still overflow. I thought it was my algorithm but switching to BigInteger got it accepted.\n\nWell.. I guess it\'s simply not so java-friendly?\n\n**If LeetCode can hear me, I would really suggest we limit test cases below Long.MAX_VALUE. Going beyond that doesn\'t bring much meanful value IMO.**\n\n```\nimport java.math.BigInteger;\n\nclass Solution {\n int MOD = 1000000007;\n public int numOfWays(int[] nums) {\n if(nums.length == 0) return 0;\n List<Integer> list = new ArrayList<>();\n for(int num : nums) list.add(num);\n return (int)(helper(list).longValue() - 1);\n }\n\n private BigInteger helper(List<Integer> nums) {\n if(nums.size() <= 2) return BigInteger.ONE;\n int root = nums.get(0);\n List<Integer> left = new ArrayList<>();\n List<Integer> right = new ArrayList<>();\n for(int i=1; i<nums.size(); i++) {\n if(nums.get(i) < root) {\n left.add(nums.get(i));\n } else {\n right.add(nums.get(i));\n }\n }\n BigInteger count = combination(nums.size() - 1, left.size());\n BigInteger leftCount = helper(left);\n BigInteger rightCount = helper(right);\n return count.multiply(leftCount).multiply(rightCount).mod(BigInteger.valueOf(MOD));\n }\n\n private BigInteger combination(int total, int num) {\n num = Math.min(num, total - num);\n if(num == 0) return BigInteger.ONE;\n\n BigInteger res = BigInteger.ONE;\n int limit = num;\n long multi = total;\n long did = 1;\n for(int i=0; i<limit; i++) {\n res = res.multiply(BigInteger.valueOf(multi--));\n res = res.divide(BigInteger.valueOf(did++));\n }\n\n return res;\n }\n}\n``` | 12 | 0 | [] | 4 |
number-of-ways-to-reorder-array-to-get-same-bst | detailed explanation - Java simple recursive divide and conquer solution | detailed-explanation-java-simple-recursi-2l2n | PLEASE UPVOTE IF THE SOLUTION WAS USEFUL !!\n\n\nThere are different steps in order to come up with this solution:\n1. logic\n2. maths formula(permutation and | niranjvin | NORMAL | 2021-09-16T16:55:35.808679+00:00 | 2021-09-17T16:13:03.670989+00:00 | 2,677 | false | ***PLEASE UPVOTE IF THE SOLUTION WAS USEFUL !!***\n\n\nThere are different steps in order to come up with this solution:\n1. logic\n2. maths formula(permutation and combination)\n3. algorithm - divide and conquer\n4. optimisation(space) - modular inverse\n5. optimisation(time) - moduler exponentiation\n\nI will explain the first 3 steps : \n\n**Logic**\nConsider base case for array ``` 5 1 3 2 4 7 9 8 6```\n-> 5 would be the root\n-> ```1 3 2 4 ``` say ```A``` are less than 5 and ```7 9 8 7 ``` say ```B``` are greater than 5\n-> at this point you can say that ```A``` will always be to left of ```5``` and ```B``` will always be to the right in the constructed binary tree.\n->So, relative positions of ```A``` and ```B``` dont matter. (don\'t mix elements within A and within B yet, we will solve this as a part of sub problems)\n-> how many ways can you mix in ```A``` and ```B``` so that relative positions within their respective sub arrays remains the same ?\n\n**Math Formula**\n-> size of ```A``` is ```na``` and ```B``` is ```nb``` respectively.\n-> You can look up for ```Identical objects into distinct bins``` on google and relate it to this question. \n-> Numbers in ```A``` can be considered as identical since you cannot permute amongst themselves\n-> There are ```nb + 1``` distinct bins because ```na``` identical nums can be in any of these ```nb+1``` distinct bins. (.ie. say ```B``` is ```1 2 3``` , there are ```4``` places where you can keep other numbers from ```A```)\n->The formula for such a senario is ```Suppose there are n identical objects to be distributed among r distinct bins. This can be done in precisely (n+r-1) C (r-1) ways.```\n\n***Algorithm***\n\n--> We have solved only for the case considering the root. Now, all you need to do is figure out how many ways with which ```A``` and ```B``` can be permuted independently and multiply everything.\n--> ```(na+nb+1-1) C (nb+1-1) * ans for A * ans for B```\n\n\n```\nclass Solution {\n \n private static long mod = 1000000007;\n private long[] inverse = new long[10001];\n \n public int numOfWays(int[] nums) {\n inverseFunc();\n \n List<Integer> list =new ArrayList<>();\n for(int n : nums){\n list.add(n);\n }\n return (int)((num(list)-1)%mod);\n }\n \n public long num(List<Integer> nums){\n \n if(nums == null || nums.size() <= 2) return 1;\n \n \n int root = nums.get(0);\n List<Integer> lessThan = new ArrayList<>();\n List<Integer> greaterThan = new ArrayList<>();\n \n for(int val : nums){\n if(val > root){\n greaterThan.add(val);\n } else if(val < root){\n lessThan.add(val);\n }\n }\n \n return ((((comb(lessThan.size() + greaterThan.size(), greaterThan.size()))%mod) * num(lessThan))%mod * num(greaterThan))%mod;\n }\n \n \n public long comb(int a, int b){\n if(a <= 0 || b <= 0) return 1;\n \n long ans = 1;\n for(int i = 1; i<=b;i++){\n ans = (ans * a)%mod;\n a--;\n }\n \n while(b>=1){\n ans = (ans * inverse[b--])%mod;\n }\n return ans;\n }\n \n \n \nvoid inverseFunc(){\n for(int i = 1; i<= 1000;i++){\n inverse[i] = power(i, mod-2, mod)%mod;\n }\n} \n \n \nlong power(long x, long y, long p){\n long res = 1;\n \n x = x % p; \n \n if (x == 0)\n return 0;\n \n while (y > 0)\n {\n \n if ((y & 1) != 0)\n res = (res * x) % p;\n \n y = y >> 1;\n x = (x * x) % p;\n }\n return res;\n }\n \n}\n``` | 10 | 0 | ['Divide and Conquer', 'Java'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Python 3 || 9 lines, recursion || T/S: 99% / 87% | python-3-9-lines-recursion-ts-99-87-by-s-0j1x | \nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n\n def dp(nums: List[int]) -> int:\n\n n = len(nums)\n if n < | Spaulding_ | NORMAL | 2023-06-16T07:38:58.543443+00:00 | 2024-06-06T06:20:25.584021+00:00 | 1,286 | false | ```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n\n def dp(nums: List[int]) -> int:\n\n n = len(nums)\n if n < 3: return 1\n root, left, right = nums[0], [], []\n\n for x in nums:\n if x < root: left .append(x)\n elif x > root: right.append(x)\n\n return dp(left) * dp(right) * comb(n-1, len(left))\n\n return (dp(nums)-1) %1_000_000_007\n```\n[https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/submissions/1279185337/](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/submissions/1279185337/)\n\n | 9 | 0 | ['Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Combination formula : C(m,n) = C(m-1,n) + C(m-1,n-1). Pre compute | combination-formula-cmn-cm-1n-cm-1n-1-pr-xgtb | C(m,n) = C(m-1,n) + C(m-1,n-1)\nC(m,n) represents the formula for combinations.\n\n\npublic class Solution\n{\n long mod = (long)Math.Pow(10, 9) + 7;\n pu | leoooooo | NORMAL | 2020-08-30T09:43:30.257151+00:00 | 2020-08-30T09:50:17.591332+00:00 | 1,301 | false | C(m,n) = C(m-1,n) + C(m-1,n-1)\nC(m,n) represents the formula for combinations.\n\n```\npublic class Solution\n{\n long mod = (long)Math.Pow(10, 9) + 7;\n public int NumOfWays(int[] nums)\n {\n int n = nums.Length;\n long[,] dp = new long[n, n];\n for (int i = 0; i < n; i++)\n {\n dp[i, 0] = 1;\n for (int j = 1; j <= i; j++)\n {\n dp[i, j] = (dp[i - 1, j - 1] + dp[i - 1, j]) % mod;\n }\n }\n return (int)Helper(nums, dp) - 1;\n }\n\n private long Helper(IList<int> nums, long[,] dp)\n {\n if (nums.Count < 2) return 1;\n var left = nums.Where(x => x < nums[0]).ToList();\n var right = nums.Where(x => x > nums[0]).ToList();\n\n long res = dp[nums.Count - 1, left.Count] % mod;\n res = res * Helper(left, dp) % mod;\n res = res * Helper(right, dp) % mod;\n\n return res;\n }\n}\n``` | 9 | 1 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ | Dynamic Programming | | c-dynamic-programming-by-ashish_madhup-fgwz | Intuition\n Describe your first thoughts on how to solve this problem. Upon reviewing the provided code, it appears to be a solution to a problem that involves | ashish_madhup | NORMAL | 2023-06-16T06:31:27.994920+00:00 | 2023-06-16T06:32:15.124201+00:00 | 2,538 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->Upon reviewing the provided code, it appears to be a solution to a problem that involves counting the number of ways to arrange a given sequence of numbers. The solution seems to be using a combination formula and a recursive approach to calculate the desired result.\n\nThe code initializes a 2D vector called `comb` with dimensions `(n + 1) \xD7 (n + 1)`, where `n` is the size of the input vector `nums`. This vector will be used to store the combination values for later calculations.\n\nThe outer loop iterates from 1 to `n` and the inner loop iterates from 1 to `i`. It populates the `comb` vector using the formula `(comb[i - 1][j - 1] + comb[i - 1][j]) % 1000000007`. This formula calculates the combination value `C(i, j)` by summing the combination values of the previous row and the previous row with an offset of -1.\n\nAfter initializing the `comb` vector, the code defines a lambda function `dfs` that takes a reference to a vector `nums` and returns an integer. This function recursively divides the input vector into two parts, `left` and `right`, based on whether each element is less than or greater than the first element of the vector. It calculates the number of arrangements for each subvector and multiplies them together, considering the combination values from the `comb` vector.\n\nFinally, the main function `numOfWays` calls the `dfs` function on the input vector `nums` and subtracts 1 from the result before returning it.\n\nOverall, the code aims to count the number of ways to arrange the elements of the `nums` vector according to certain conditions, using a combination formula and a recursive approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->The given code is implementing a recursive approach to solve a problem related to counting the number of ways to arrange a sequence of numbers. Let\'s break down the approach:\n\n1. The code initializes a 2D vector called `comb` with dimensions `(n + 1) \xD7 (n + 1)`, where `n` is the size of the input vector `nums`. This vector will be used to store precalculated combination values.\n\n2. The `comb` vector is populated using a combination formula `(comb[i - 1][j - 1] + comb[i - 1][j]) % 1000000007`. This formula calculates the combination value `C(i, j)` by summing the combination values of the previous row and the previous row with an offset of -1.\n\n3. The code defines a lambda function called `dfs` that takes a reference to a vector `nums` and returns an integer. This function is responsible for the recursive division of the input vector into two parts, `left` and `right`, based on whether each element is less than or greater than the first element of the vector.\n\n4. Within the `dfs` function, the base case is when the size of the input vector `nums` is less than or equal to 2. In this case, the function returns 1, indicating that there is only one possible arrangement.\n\n5. If the input vector size is greater than 2, the function proceeds to divide the vector into two subvectors, `left` and `right`, by comparing each element to the first element of the vector. Elements smaller than the first element are added to the `left` subvector, while elements greater than or equal to the first element are added to the `right` subvector.\n\n6. The function then calculates the number of arrangements for each subvector by recursively calling itself on the `left` and `right` subvectors. It multiplies these results together.\n\n7. Additionally, the function multiplies the result by the combination value `comb[n - 1][left.size()]`, which is obtained from the precalculated `comb` vector. This combination value represents the number of ways to arrange the elements in the subvectors `left` and `right` relative to each other.\n\n8. The final result is returned as `(int)res`, where `res` is a long long integer, and it is subtracted by 1 outside the `dfs` function before returning from the `numOfWays` function.\n\nThe approach combines the use of combination formulas and recursion to count the number of arrangements based on certain conditions. The recursive division of the vector into subvectors allows for exploring all possible arrangements and calculating the number of ways for each arrangement.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) \n {\n int n = nums.size();\n vector<vector<int>> comb(n + 1, vector<int>(n + 1));\n comb[0][0] = 1;\n for (int i = 1; i <= n; ++i) \n {\n comb[i][0] = 1;\n for (int j = 1; j <= i; ++j)\n {\n comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % 1000000007;\n }\n }\n function<int(vector<int>&)> dfs = [&](vector<int>& nums)\n {\n int n = nums.size();\n if (n <= 2) return 1;\n vector<int> left, right;\n for (int i = 1; i < n; ++i) \n {\n if (nums[i] < nums[0]) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n }\n long long res = comb[n - 1][left.size()];\n res = res * dfs(left) % 1000000007;\n res = res * dfs(right) % 1000000007;\n return (int)res;\n };\n return dfs(nums) - 1;\n }\n};\n```\n\n | 8 | 0 | ['Array', 'Dynamic Programming', 'Recursion', 'Counting', 'C++'] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | Number of Ways to Reorder Array to Get Same BST | C++ | Recursive | number-of-ways-to-reorder-array-to-get-s-vjhn | The problem could be solved using recusion as the problem could be broken down into smaller overlapping subproblems.\n\nThe first node would always be the root | tushargarg | NORMAL | 2020-08-30T04:06:53.077238+00:00 | 2020-08-30T04:20:29.153074+00:00 | 887 | false | The problem could be solved using recusion as the problem could be broken down into smaller overlapping subproblems.\n\nThe first node would always be the root node so it can\'t be rearranged to any other place. For the rest of the nodes the nodes smaller than the root node would have the same ordering and the nodes larger than the root node would also have the same ordering in the final array but the nodes could be rearranged between the larger nodes and smaller nodes.\n\n\n\nThe problem then simply becomes to find in how many ways can we c(elements smaller than root) numbers in n-1(total available places after removing the roor) places which could be calculated using nCr.\n```\nFor [3,4,5,1,2], in all arrays 3 would always stay at nums[0] as it has to be the root node\nNow, in all arrays [1,2] and [4,5] needs to be in same order as changing the order would result in change in the corresponding subtree.\n\nBut the two arrays [1,2] and [4,5] could be arranged among themselves.\nThat would simply mean we have to find 2 places for [1,2] out of the 4 availble places which means the answer would be 4C2.\n\nThen we need to recusively find the answer for [1,2] and [4,5]\n\n```\n\nC++\n\n```\nclass Solution {\npublic:\n const long long mod = 1e9+7;\n vector<long long> fact;\n void calcFact()\n {\n fact[0]=1;\n fact[1]=1;\n for(long long i=2;i<1001;i++)\n fact[i]=(fact[i-1]*i)%mod;\n }\n \n long long modInv(long long n,long long p)\n {\n if(p==0)\n return 1LL;\n long long ans=modInv(n,p/2);\n if(p&1)\n return (((ans*ans)%mod)*n)%mod;\n else\n return (ans*ans)%mod;\n }\n \n long long helper(vector<int> &nums)\n {\n if(nums.size()<=2) // if the length of array is less than equal to 2 there is only 1 way to arrange it\n return 1LL;\n vector<int> small,large; // store elements smaller and larger than the root node\n for(int i=1;i<nums.size();i++)\n {\n if(nums[i]>nums[0])\n large.push_back(nums[i]);\n else small.push_back(nums[i]);\n }\n long long ans=1;\n ans=(ans*fact[(int)nums.size()-1])%mod;\n ans=(ans*modInv(fact[(int)nums.size()-(int)small.size()-1],mod-2))%mod; // if m is prime, modular inverse is simply pow(n,m-2)\n ans=(ans*modInv(fact[(int)small.size()],mod-2))%mod; // find nCr\n ans=(ans*helper(small))%mod; //recursively solve for smaller array \n ans=(ans*helper(large))%mod; //recursively solve for smaller array\n return ans;\n }\n \n \n int numOfWays(vector<int>& nums) {\n fact=vector<long long> (1001);\n calcFact(); // maintain a factorial array to find nCr\n long long ans= helper(nums);\n ans--; // subtract 1 for the original array\n ans=(ans+mod)%mod;\n return ans;\n }\n};\n``` | 7 | 2 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Approach Explained With Observation || Easy To Understand | approach-explained-with-observation-easy-rbes | Intuition\n\nDifferent permutation that yield same bst as given \n OBSERVATION :- \n [1] ROOT IS SAME \n [2] NOW, COMES LEFT AND RIGHT PART | shubh08am | NORMAL | 2023-06-16T15:38:39.486226+00:00 | 2023-06-16T15:38:39.486252+00:00 | 1,163 | false | # Intuition\n```\nDifferent permutation that yield same bst as given \n OBSERVATION :- \n [1] ROOT IS SAME \n [2] NOW, COMES LEFT AND RIGHT PART \n [3] RELATIVE POSITION IS FIXED OF LEFT AND RIGHT PART\n [4] COUNT NO OF PERMUTATION \n [5] LEFT N-1 PLACE TO BE FILLED \n [6] LET NO. OF ELEMENT IN RIGHT or LEFT BE X THAN n-1Cx -1 COMBINATION POSSIBLE\n ALSO NEED TO TAKE IN COUNT LEFT AND RIGHT SUBTREE COMBINATION FURTHER\n [7] -1 BECAUSE GIVEN BST ALSO COUNTED IN VALID \n [8] EVERY SUBTREE CAN BE CONSIDERED INDIVIDUALLY AND COMBINATION FOR IT \n CAN BE FOUND RECURSIVELY\n [9] PRECOMPUTE COMBINATION LOGIC EFFECTIVELY USING PASCAL TRIANGLE LOGIC\n \n```\n# Approach\n``` \nRECURSION + DP + MATHS\n```\n\n# Complexity\n- Time complexity:\n$$O(N^2)[RECURSION]+O(N^2) [PASCAL]$$ \n\n- Space complexity:\n$$O(N^2)$$ \n\n# Code\n```\nconst int mod = 1e9+7;\nclass Solution {\npublic:\n void PascalTriangle(int n,vector<vector<int>>&dp){\n for(int i=0;i<=n;i++){\n dp[i] = vector<int>(i+1,1); //initially all 1 \n //Now Apply combination logic of adding prev_row and prev_col \n for(int j=1;j<i;j++){\n dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%mod;\n }\n }\n }\n int dfs(vector<int>&nums,vector<vector<int>>&dp){\n vector<int>leftSubTree , rightSubTree ; \n int n = nums.size() ; \n\n //1 COMBINATION OF BST POSSIBLE\n if(n<3) return 1;\n\n //FIND LEFT AND RIGHT SUBTREE FOR ROOT I.E nums[0] \n for(int i=1;i<n;i++){\n if(nums[i]>=nums[0]) rightSubTree.push_back(nums[i]);\n if(nums[i]<nums[0]) leftSubTree.push_back(nums[i]);\n } \n\n int left = dfs(leftSubTree,dp)%mod ; \n int right = dfs(rightSubTree,dp)%mod ; \n int ele_atLeft = leftSubTree.size() ; \n\n // n-1Cele_atLeft * left * right \n return (1ll * (1ll * dp[n-1][ele_atLeft]*1ll * left)%mod * right)%mod ; \n }\n int numOfWays(vector<int>& nums) {\n // Different permutation that yield same bst as given \n //T.C -> O(N^2)[RECURSION]+O(N^2) [PASCAL]\n //S.C -> O(N^2)[D.P]\n int n = nums.size() ; \n vector<vector<int>>dp(n+1) ; \n PascalTriangle(n,dp);\n int ways = dfs(nums,dp)-1; // -1 BECAUSE GIVEN BST ALSO COUNTED IN VALID \n return ways;\n }\n};\n```\n```\nIf you find this solutions to be helpful do upvote..It keeps me motivated :)\n``` | 5 | 0 | ['Math', 'Dynamic Programming', 'Recursion', 'Combinatorics', 'C++'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Simple Python Solution O(n^2) | simple-python-solution-on2-by-niraj243-vn9m | Code\n\nclass Solution(object):\n def numOfWays(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n self.ans | niraj243 | NORMAL | 2023-06-16T10:21:00.276888+00:00 | 2023-06-16T15:26:37.172771+00:00 | 464 | false | # Code\n```\nclass Solution(object):\n def numOfWays(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n self.ans = 1\n mod = 1000000007\n class BST:\n self.right = None\n self.left = None\n self.val = None\n self.below_count = None\n self.cont_ans = None\n\n def __init__(self,left=None,right=None,val=None):\n self.right = right\n self.left = left\n self.val = val\n\n def insert(root,val):\n if root.val == None:\n root.val = val\n return\n if val < root.val:\n if root.left == None:\n root.left = BST(val=val)\n else:\n insert(root.left,val)\n else:\n if root.right == None:\n root.right = BST(val=val)\n else:\n insert(root.right,val)\n\n def bel_count(root):\n if root is None:\n return 0\n root.below_count = 1\n root.below_count += bel_count(root.left)\n root.below_count += bel_count(root.right)\n return root.below_count\n\n def iot(root):\n if root is None:\n return\n iot(root.left)\n self.ans = (self.ans*root.cont_ans)%mod\n iot(root.right)\n\n\n def nck(n,k):\n if n<=0 or k<=0 or k>=n:\n return 1\n return factorial(n)/(factorial(k)*(factorial(n-k)))\n\n\n def get_ans(root,remain):\n if root is None:\n return\n root.cont_ans = 1\n root.cont_ans *= nck(remain,root.below_count)%mod\n root.cont_ans = root.cont_ans%mod\n get_ans(root.left,root.below_count-1)\n remain1 = root.below_count-1\n if root.left is not None:\n remain1 = remain1 - root.left.below_count\n get_ans(root.right,remain1)\n\n root = BST()\n for num in nums:\n insert(root,num)\n bel_count(root)\n get_ans(root,len(nums))\n iot(root)\n\n return self.ans-1\n\n\n``` | 5 | 0 | ['Binary Search Tree', 'Combinatorics', 'Python'] | 7 |
number-of-ways-to-reorder-array-to-get-same-bst | Best Solution ππͺπΌ | best-solution-by-kchheda97-c48f | Approach\nThe approach used in the code involves a depth-first search (DFS) algorithm. The dfs function takes three parameters: i represents the current index, | kchheda97 | NORMAL | 2023-06-16T00:23:14.432201+00:00 | 2023-06-16T01:12:22.338322+00:00 | 236 | false | # Approach\nThe approach used in the code involves a depth-first search (DFS) algorithm. The dfs function takes three parameters: i represents the current index, l represents the lower bound, and h represents the upper bound.\n\nThe function checks if the upper bound h is one greater than the lower bound l. If so, it means there are no more elements to consider, and the function returns 1.\n\nOtherwise, the function checks if the value at index i is between l and h. If it is, it recursively calls dfs twice: once with the left subarray (from l to A[i]) and once with the right subarray (from A[i] to h). It also calculates the number of combinations between the left and right subarrays using math.comb and multiplies it with the recursive results.\n\nIf the value at index i is not between l and h, the function makes a recursive call with the same index but updates only the upper bound.\n\nFinally, the function returns the result of the recursive calls subtracted by 1.\n\nThe numOfWays function initializes some variables and then calls dfs with the initial parameters.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: The time complexity depends on the number of recursive calls made. Each recursive call reduces the problem size, so the time complexity can be expressed as O(2^n), where n is the length of the input list A.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity is determined by the depth of the recursive calls, which can go up to n. Therefore, the space complexity is O(n).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numOfWays(self, A):\n n = len(A)\n mod = 10 ** 9 + 7\n\n def dfs(i, l, h):\n if h == l + 1:\n return 1\n if l < A[i] < h:\n return (dfs(i + 1, l, A[i]) * dfs(i + 1, A[i], h) * math.comb(h - l - 2, A[i] - l - 1)) % mod\n return dfs(i + 1, l, h)\n \n return dfs(0, 0, n + 1) - 1\n\n```\n\n### *Kindly Upvote\u270C\uD83C\uDFFC* | 5 | 0 | ['Python3'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ explanation for 1569 | c-explanation-for-1569-by-tktripathy-qyan | How does this work? Explaining it so that it might help some folks.\n\n\nCase I: Consider a BST: [4,2,1,3,5] \n 4 [ level 0 ]\n 2 | tktripathy | NORMAL | 2020-09-06T01:14:16.962024+00:00 | 2020-09-06T06:42:58.247211+00:00 | 733 | false | How does this work? Explaining it so that it might help some folks.\n\n```\nCase I: Consider a BST: [4,2,1,3,5] \n 4 [ level 0 ]\n 2 5 [ level 1 ]\n 1 3 \nWe get these valid ways at level 0:\n [4,2,1,3,5] \n [4,2,1,5,3]\n [4,2,5,1,3]\n [4,5,2,1,3]\n \n [4,2,3,1,5]\n [4,2,3,5,1]\n [4,2,5,3,1]\n [4,5,2,3,1]\n \nThe root, 4, stays fixed.\n\nCase II: If we look at the left subtree, [2,1,3] at level 1:\n 2\n 1 3 \n... has the following valid ways:\n [2,1,3]\n [2,3,1]\n\nThe root, 2, stays fixed.\n\nCase III. Right subtree, [5] at level 1 has no children.\n 5\n... has the following valid ways:\n [5]\n```\nClearly, Case I is dependent on case II and III.\n\nAt the crux of this problem is a fundamental math problem of merging two sequences to generate a number of new sequences where the order of the two sequences are not disturbed. This explains the problem: https://math.stackexchange.com/questions/666288/number-of-ways-to-interleave-two-ordered-sequences/ - the formula to use is *nCr* where n is the number of all elements in the two sequences and r is the number of elements in the first sequence.\n\n```\nMapping it to our problem (Case II), given the ordered sequences [1] and [3] how many ways to create a valid sequence \n(without disturbing the order of the first and second sequence):\n [1, 3]\n [3, 1]\n\nn = 2, r = 1, 2C1 = 2 <--- x (i.e n = number of left and right subtree nodes, r = number of left subtree nodes)\n\nIn Case III, there are no children.\nn = 0, r = 0, 0C0 = 1 <--- y (i.e n = number of left and right subtree nodes, r = number of left subtree nodes)\n\nMapping it to Case I, given the ordered sequences [2,1,3] and [5] how many ways to create a valid sequence \n(without disturbing the order of the first and second sequence):\n [2,1,3,5] \n [2,1,5,3]\n [2,5,1,3]\n [5,2,1,3]\n\nn = 4, r = 3. 4C3 = 4 <--- z (i.e n = number of left and right subtree nodes, r = number of left subtree nodes)\n\n... and given the ordered sequences [2,3,1] and [5]:\n [2,3,1,5]\n [2,3,5,1]\n [2,5,3,1]\n [5,2,3,1]\n\nn = 4, r = 3. 4C3 = 4\n```\nAs can be observed, the total number of valid sequences at any node can be derived by multiplying the sequences computed at itself and its children subtrees. At the root of the tree in Case I, this is simply x * y * z = 8. This is reflected in the recursion:\n```\n return c * DFS(l) % M * DFS(r) % M;\n```\nThe code follows:\n```\nclass Solution {\npublic:\n /*\n * Formula for nCr = n! / r! * (n - r)!\n * We will use Pascal\'s triangle\n */\n int M = 1000000007; /* calculations bounded by this */\n long l[1001][1001] = { 0 }; bool init = false;\n\n long combination(int n, int r) {\n if (init/*ialized*/ == true) return l[n][r];\n l[0][0] = 1; /* We know 0C0 = 1, otherwise l[0] row is all 0s */\n for (int i = 1; i < 1001; i++) {\n l[i][0] = 1; /* Set every nCr = 1 where r = 0 */\n /* Set value for the current cell of Pascal\'s triangle i.e iC{1 ... i} */\n for (int j = 1; j < i + 1; j++) { \n l[i][j] = (l[i - 1][j - 1] + l[i - 1][j]) % M; \n } \n }\n init = true;\n return l[n][r];\n }\n\n long DFS(vector<int>& nums)\n {\n if (nums.size() < 3) return 1; /* 1C1, 1C0, 0C0 */\n vector<int> l, r;\n /* Separate into left subtree sequence and right subtree sequence of nodes */\n for (auto e : nums) { if (e > nums[0]) l.push_back(e); if (e < nums[0]) r.push_back(e); }\n /* Use nCr formula for merging sequences */\n long c = combination(l.size() + r.size(), l.size());\n /* Recur down */\n return c * DFS(l) % M * DFS(r) % M;\n }\n \n int numOfWays(vector<int>& nums) {\n return (int)DFS(nums) - 1 /* one sequence already given in nums */;\n }\n};\n```\nPS: I initially wanted to use:\n```\n /* Factorial */\n long factorial(long n) { return (n == 1 || n == 0) ? 1 : (n * factorial(n - 1)); }\n \n long combination1(int n, int r) {\n if (l[n][r]) return l[n][r];\n /* Formula for nCr = n! / r! * (n - r)! */\n l[n][r] = factorial(n) / (factorial(r) * factorial(n - r)); /* memoize */\n return l[n][r];\n }\n```\nThis works up to certain test cases and breaks because of no mod in it. Adding a mod in factorial() does not give the correct answer. So, it looks like this problem only works if the Pascal\'s triangle method is used and mod is done during addition and not at multiplication. | 5 | 0 | [] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ || WITH FULL EXPLANATION || EASY | c-with-full-explanation-easy-by-neha0312-gxm7 | We know that in bst all the nodes to the left are less than the root node and all the nodes to the right are greater than the root node. So in order to create s | neha0312 | NORMAL | 2023-06-16T05:25:03.407422+00:00 | 2023-06-16T05:25:03.407448+00:00 | 424 | false | We know that in bst all the nodes to the left are less than the root node and all the nodes to the right are greater than the root node. So in order to create same bst we will have to use same root as first node and consider relative ordering independently of left and right sub part.\n\nIt took me while to understand the concept so this is the explanation!\nlets consider example\n[3,4,5,1,2]\nhere root=3;\nleft=[1,2];\nright=[4,5];\nnow to get same bst 1 should always appear before 2.\nin right part 4 should appear before 5.\nbut there is no restriction on order of left and right ordering.Like 4 and 2 can occur in any order.\nNow to get total results first of all the the length of left=l;\nlength of right= r;\ntotal length= l+r;\nwe have l+r position out of which l position has to be selected for the left elements and they will appear in same order.\nso no of ways= length(c)left\nnow for left and right subtree we call the recursive function and multiply the total result.\n\n```\nclass Solution {\npublic:\n int mod=1e9+7;\n int countBST(vector<int>& nums) {\n if (nums.size() <= 2)\n return 1;\n\n vector<int> left, right;\n int root = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i] < root)\n left.push_back(nums[i]);\n else\n right.push_back(nums[i]);\n }\n\n long long l = countBST(left); \n long long r = countBST(right);\n\n // Calculate the number of combinations using the Catalan number formula\n long long tc = binomialCoefficient(left.size() + right.size(), left.size());\n\n return (l * r % 1000000007 * tc % 1000000007);\n }\n \n\n long long binomialCoefficient(int n, int k) {\n const int MOD = 1e9 + 7;\n\n vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, 0));\n dp[0][0] = 1;\n\n for (int i = 1; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= min(i, k); j++) {\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD;\n }\n }\n\n return dp[n][k];\n }\n int numOfWays(vector<int>& nums) {\n const int MOD = 1e9 + 7;\n return (countBST(nums) - 1 + MOD) % MOD;\n \n }\n};\n\n\n | 4 | 0 | ['Binary Search Tree', 'C', 'Combinatorics'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | w Explanation||C++/Python using Math Pascal's triangle/comb Beats 96.74% | w-explanationcpython-using-math-pascals-yweky | Intuition\n Describe your first thoughts on how to solve this problem. \nThe first element in array must be the root. Then divide the array into left subtree an | anwendeng | NORMAL | 2023-06-16T05:18:10.415690+00:00 | 2023-06-16T18:29:34.470713+00:00 | 1,442 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first element in array must be the root. Then divide the array into left subtree and right subtree! \n\nUse recursion, if the subproblems for left subtree and right subtree are solved, with the returning number l and r, Use the following formula:\n$$\nTotalNumber=l\\times r\\times C^{N-1}_{Len(left\\_subtree)}-1\n$$\nto solve the problem! Remember modulo 10**9+7 \n\nPlease turn on the English subtitles if neccessary!\n[https://youtu.be/eS-Po5QJE24](https://youtu.be/eS-Po5QJE24)\n# Why multiplication? The fundamental principle of counting/rule of product or multiplication principle says:\n> if there are a ways of doing something and b ways of doing another thing, then there are a \xB7 b ways of performing both actions.\n\n# Why the binomial number $C^{N-1}_{Len(left\\_subtree)}$?\nQ: Let N = len(nums). The position for the root is always at index 0. While you can change the positions of elements in the left and right subtrees, you need to maintain the orderings within each subtree. Therefore, there are N-1 available places to position either the left or right subtree. The count of possible arrangements is exactly given by $C^{N-1}_{Len(left\\_subtree)}$!\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe computation for the binomial number $C^n_k$ from n choose k is using [Pascal\'s triangle](https://leetcode.com/problems/pascals-triangle/solutions/3201092/best-c-solution-via-pascal-s-identity-c-i-j-c-i-i-j-beats-100/)!\n\nThis test case makes using direct method computing $C^{N-1}_{Len(left\\_subtree)}$ impossible in C++, even using unsigned long long! But in python there is a function comb. \n```\n[74,24,70,11,6,4,59,9,36,82,80,30,46,31,22,34,8,69,32,57,18,21,37,83,55,38,41,72,48,65,27,60,73,58,68,50,16,77,75,20,81,3,61,13,10,29,62,49,12,66,39,45,28,40,42,52,78,56,44,17,14,67,35,26,19,5,63,51,43,23,79,2,54,47,76,53,7,25,64,33,1,15,71]\n```\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code with Explanation in comments\n```\nclass Solution {\npublic:\n long Mod = 1e9 + 7;\n // Calculate C_{n} choose k using Pascal\'s equation\n vector<vector<long>> C; // Matrix to store calculated binomial coefficients\n \n long compute_C_N_choose_K(int N, int K) {\n if (K > N / 2)\n K = N - K; // C_N choose K = C_N choose N-K\n \n C.assign(N + 1, vector<long>(K + 1, 0)); \n // Initialize the matrix with zeros\n \n for (int i = 0; i <= N; i++) {\n C[i][0] = 1; // Set the first column of each row to 1\n \n for (int j = 1; j <= min(i, K); j++)\n C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % Mod; \n // Calculate binomial coefficient using Pascal\'s equation\n }\n \n return C[N][K]; // Return the computed binomial coefficient\n }\n\n long Subproblem(vector<int>& nums) {\n int n = nums.size();\n \n if (n <= 2)\n return 1; \n// Base case: If the number of elements is less than or equal to 2, \n//there is only one way to split\n \n vector<int> left, right;\n int root = nums[0]; // Choose the first element as the root\n \n // Split the remaining elements into left and \n //right parts based on their values compared to the root\n for (int i = 1; i < n; i++) {\n if (root < nums[i])\n right.push_back(nums[i]); \n// Add the element to the right part if it is greater than the root\n\n else\n left.push_back(nums[i]); \n// Add the element to the left part if \n//it is less than or equal to the root\n }\n \n long r = Subproblem(right) % Mod; \n// Recursively calculate the number of ways for the right part\n\n long l = Subproblem(left) % Mod; \n// Recursively calculate the number of ways for the left part\n \n return compute_C_N_choose_K(n - 1, left.size()) * r % Mod * l % Mod; \n// Compute the total number of ways based on binomial coefficients \n// and the number of ways for left and right parts\n }\n\n int numOfWays(vector<int>& nums) {\n return Subproblem(nums); \n// Start the recursive computation by calling the Subproblem function\n }\n};\n\n```\n# 2nd Solution w SC O(N) & twice faster than 1st one\n```\nclass Solution {\npublic:\n int Mod=1e9+7;\n //Calcute C_{n} choose k by Pascal\'s equation\n \n int compute_C_N_choose_K(int N, int K){\n if (K>N/2) K=N-K;//C_N choose K =C_N choose N-K\n vector<int> C_N(K+1, 0), prevC(K+1, 0);\n for(int i=0; i<=N; i++){\n C_N[0]=1;\n for(int j=1; j<=min(i, K);j++){\n C_N[j]=((long)prevC[j-1]+prevC[j])%Mod; \n }\n prevC=C_N; \n }\n return C_N[K];\n }\n\n long Subproblem(vector<int>& nums){\n int n=nums.size();\n if (n<=2) return 1;\n vector<int> left, right;\n int root=nums[0];\n for (int i=1; i<n; i++){\n if (root<nums[i]) right.push_back(nums[i]);\n else left.push_back(nums[i]);\n }\n long r=Subproblem(right), l=Subproblem(left);\n return compute_C_N_choose_K(n-1, left.size())*r%Mod*l%Mod;\n\n }\n int numOfWays(vector<int>& nums) {\n return (Subproblem(nums)-1)%Mod;\n }\n};\n```\n# Python solution Runtime 155 ms Beats 96.74%\n```\nclass Solution: \n def numOfWays(self, nums: List[int]) -> int:\n Mod=10**9+7\n import math\n def Subproblem(nums: List[int]):\n n=len(nums)\n if n<=2: return 1\n root=nums[0]\n left=[]\n right=[]\n for y in nums[1:]:\n if y<root: left.append(y)\n else: right.append(y)\n return Subproblem(right)*Subproblem(left)%Mod*math.comb(len(nums)-1, len(left))%Mod\n return int((Subproblem(nums)-1)%Mod)\n``` | 4 | 0 | ['Math', 'Divide and Conquer', 'Dynamic Programming', 'C++', 'Python3'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ || Explained | c-explained-by-punityadav_2003-t686 | \n\n# Approach\n The solution first calculates the binomial coefficients using dynamic programming and stores them in a 2D vector comb. \nThen, it defines a rec | PunitYadav_2003 | NORMAL | 2023-06-16T02:37:49.478963+00:00 | 2023-06-16T02:37:49.478989+00:00 | 2,976 | false | \n\n# Approach\n The solution first calculates the binomial coefficients using dynamic programming and stores them in a 2D vector comb. \nThen, it defines a recursive function dfs that takes as input a subarray of nums and returns the number of ways to reorder that subarray such that the BST formed is identical to the original BST.\n The function dfs first checks if the size of the input subarray is less than or equal to 2, in which case it returns 1.\n Then, it separates the elements of the input subarray into two subarrays left and right, where left contains all elements that are less than the first element of the input subarray and right contains all elements that are greater than or equal to the first element of the input subarray. \nThe function then calculates the result as the product of the binomial coefficient comb[n - 1][left.size()], dfs(left), and dfs(right), modulo 1000000007. Finally, it returns the result cast to an integer. The main function calls dfs(nums) and returns its result minus 1\n\n# Complexity\n- Time complexity:O(n^2)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numOfWays(vector<int>& nums) {\n int n = nums.size();\n vector<vector<int>> comb(n + 1, vector<int>(n + 1));\n comb[0][0] = 1;\n for (int i = 1; i <= n; ++i) {\n comb[i][0] = 1;\n for (int j = 1; j <= i; ++j) {\n comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % 1000000007;\n }\n }\n function<int(vector<int>&)> dfs = [&](vector<int>& nums) {\n int n = nums.size();\n if (n <= 2) return 1;\n vector<int> left, right;\n for (int i = 1; i < n; ++i) {\n if (nums[i] < nums[0]) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n }\n long long res = comb[n - 1][left.size()];\n res = res * dfs(left) % 1000000007;\n res = res * dfs(right) % 1000000007;\n return (int)res;\n };\n return dfs(nums) - 1;\n }\n};\n \n``` | 4 | 0 | ['Dynamic Programming', 'Combinatorics', 'C++'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | βDP Recursion using Python π₯Layman's Code π₯β | dp-recursion-using-python-laymans-code-b-88xa | An upvote would be appreciating...\n--\n# Intuition\nThe problem asks us to find the number of ways to reorder an array in order to obtain the same binary searc | ShreejitCheela | NORMAL | 2023-06-16T01:57:11.736848+00:00 | 2023-06-16T01:59:40.435007+00:00 | 1,013 | false | **An upvote would be appreciating...**\n--\n# Intuition\nThe problem asks us to find the number of ways to reorder an array in order to obtain the same binary search tree (BST) structure. We can approach this problem by counting the number of valid BSTs that can be formed from the given array.\n\n# Approach\nTo solve this problem, we can use a recursive approach. We define a helper function `countBST` that takes an array of numbers as input and returns the count of valid BSTs that can be formed from that array. The base case occurs when the array has two or fewer elements, in which case there is only one valid BST.\n\nIn the recursive case, we choose the first element of the array as the root of the BST. We partition the remaining elements into two subarrays: one containing elements smaller than the root and the other containing elements greater than the root. We then recursively count the number of valid BSTs that can be formed from each subarray and multiply them together. Finally, we multiply this count by the number of combinations of choosing positions for the smaller and larger elements in the array.\n\nTo calculate the number of combinations, we define two helper functions: `fact` and `combs`. The `fact` function calculates the factorial of a given number modulo `10^9 + 7`. The `combs` function calculates the combination of choosing `r` elements from `n` elements using the factorial function and modular arithmetic.\n\nFinally, we subtract 1 from the total count of BSTs since we are not considering the original ordering of the array.\n\n# Complexity\n- Time complexity: O(n^2), where n is the number of elements in the input array. This is because for each recursive call, we partition the array into two subarrays, resulting in a total of n recursive calls.\n- Space complexity: O(n), where n is the number of elements in the input array. This is because we use recursion, which consumes memory on the call stack proportional to the depth of the recursion.\n\nHere is my code:\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n m = (10**9) + 7\n\n def fact(n):\n r = 1\n for i in range(1, n+1):\n r = (r * i) % m\n return r\n\n def combs(n, r):\n nr = fact(n)\n dr = (fact(r) * fact(n - r)) % m\n return (nr * pow(dr, m - 2, m)) % m\n\n def countBST(nums):\n if len(nums) <= 2:\n return 1\n\n left_nums = [n for n in nums if n < nums[0]]\n right_nums = [n for n in nums if n > nums[0]]\n\n left_count = countBST(left_nums)\n right_count = countBST(right_nums)\n\n return (combs(len(nums) - 1, len(left_nums)) * left_count * right_count) % m\n\n return (countBST(nums) - 1) % m\n``` | 4 | 0 | ['Dynamic Programming', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'Python3'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | Ruby: array partitioning and combinatorics | ruby-array-partitioning-and-combinatoric-dowu | 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 | lacrosse | NORMAL | 2023-03-27T20:56:07.326998+00:00 | 2023-03-27T20:56:07.327024+00:00 | 97 | false | # 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)$$ | 4 | 0 | ['Array', 'Math', 'Combinatorics', 'Ruby'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | O(NlogN) asymptotically OPTIMAL solution. | onlogn-asymptotically-optimal-solution-b-t8oh | O(N^2) isn\'t optimal\n\nBefore reading this, you should understand the recursive solution by reading other posts (C++, Java, doing division is a bit complicate | cai_lw | NORMAL | 2020-08-30T21:15:53.274127+00:00 | 2020-08-31T00:17:16.300446+00:00 | 575 | false | **O(N^2) isn\'t optimal**\n\nBefore reading this, you should understand the recursive solution by reading other posts ([C++](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819369/C%2B%2B-Just-using-recursion-very-Clean-and-Easy-to-understand-O(n2)), [Java](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819725/Java-Clean-code-uses-Yang-Hui\'sPascal\'s-Triangle-With-Explanation), [Python](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819282/Python-O(n2)-post-order-traversal)).\n\nOnce the BST is built, the recursion only takes O(N) steps and is optimal. However, most of the solutions here are O(N^2) because of two suboptimal steps:\n1. Naive insertion into unbalanced BST is O(N) in the worst case, so tree-building is O(N^2).\n2. Pre-computing all combination C(m,n) (aka Pascal\'s triangle) takes O(N^2)\n\nIn this post I\'ll show the optimal algorithms to the above two steps, the first one O(NlogN) and the second O(NlogP) (where P=10^9+7), making the overall complexity O(NlogN) (since P is a constant).\n\n**Building unbalanced BST with the help of balanced BST**\n\nReflecting on the BST insertion algorithm, it\'s not hard to notice that **the parent of the newly inserted number is either the next larger number or the next smaller number**.\n\nFor example, if numbers in the BST are [1,2,4,5], and the new number is 3, then regardless of the shape of the BST, 3\'s parent must be either 2 or 4.\n\nProof by contradiction is simple: if that\'s not true, there are numbers between the new number and its parent, which by the definition of BST have to be the children of the new number, violating the BST insertion algorithm that the new number is a leaf node.\n\nFurthermore, **there is always one and only one available position for insertion** between the two possibilities: "right child of the next smaller number" and "left child of the next larger number". Proof: since there are no number between "the next smaller number" and "the next larger number", either "the next larger number" is in the right subtree of "the next smaller number", or "the next smaller number" is in the left subtree of "the next larger number". In both cases, one of the two possible positions is occupied by an existing subtree.\n\nWith the observations above, we can use a balanced BST (`map` in C++ or `TreeMap` in Java) that can find "next larger/smaller number" in O(logN). With the help of a balanced BST, we can insert a number into an unbalanced BST in O(logN), thus building the whole unbalanced BST in O(NlogN). Below is my C++ code for tree-buliding:\n\n```C++\nclass Solution {\n struct Tree{\n Solution::Tree *l,*r;\n int v;\n Tree(int v):l(nullptr),r(nullptr),v(v){}\n };\n void insert(map<int,Tree*>& mp,int v){\n Tree* leaf=new Tree(v);\n auto it=mp.lower_bound(v);\n if(it!=mp.end()&&!it->second->l){\n it->second->l=leaf;\n }\n else{\n it--;\n it->second->r=leaf;\n }\n mp[v]=leaf;\n }\npublic:\n int numOfWays(vector<int>& nums) {\n map<int,Tree*> mp;\n Tree* root=new Tree(nums[0]);\n mp[nums[0]]=root;\n for(int i=1;i<nums.size();i++)\n insert(mp,nums[i]);\n // ...\n }\n};\n```\n**Combinations formula and modular inverse**\n\nWe all know the formular for combinations, or number of ways of selecting `m` items from `n` items: `C(m,n)=n!/m!/(n-m)!`. If we pre-compute all factorials from 1 to N, we can compute any `C(m,n)` in O(1) with this formula.\n\nHowever, in modular arithmetics ("return the result modulo P"), doing division is a bit complicated. Unlike addition/subtraction/multiplication, `(a/b)%P` is not equal to `(a%P)/(b%P)`. It turns out that you need to compute `a*inv(b,P)%P` instead, where `inv(b,P)` is called the [modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of b modulo P.\n\nThere are [two algorithms modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Computation), both of which are O(logP) for small P that fits in a machine word. Thus, we can pre-compute all factorials and their modular inverses from 1 to N in O(NlogP), and then compute any `C(m,n)` in O(1).\n1. Extended Euclidean algorithm\n2. Exponentiation by squaring and Fermat\'s Little Theorem (`a^(P-2)=a^-1 (mod P)`)\n\nI personally prefer the second one, although it only works when P is prime. Below is the C++ code.\n```C++\ntypedef long long ll;\nconst ll P=1000000007;\nll pow(ll a,ll n){\n\tif(n==1)return a;\n\tll half=pow(a,n/2);\n\tll ret=half*half%P;\n\tif(n%2)ret=ret*a%P;\n\treturn ret;\n}\nll inv(ll a){\n\treturn pow(a,P-2);\n}\n```\n**Full code in C++**\n```C++\nclass Solution {\n struct Tree{\n Solution::Tree *l,*r;\n int v;\n Tree(int v):l(nullptr),r(nullptr),v(v){}\n };\n void insert(map<int,Tree*>& mp,int v){\n Tree* leaf=new Tree(v);\n auto it=mp.lower_bound(v);\n if(it!=mp.end()&&!it->second->l){\n it->second->l=leaf;\n }\n else{\n it--;\n it->second->r=leaf;\n }\n mp[v]=leaf;\n }\n typedef long long ll;\n const ll P=1000000007;\n vector<ll> fac,invfac;\n ll pow(ll a,ll n){\n if(n==1)return a;\n ll half=pow(a,n/2);\n ll ret=half*half%P;\n if(n%2)ret=ret*a%P;\n return ret;\n }\n ll inv(ll a){\n return pow(a,P-2);\n }\n ll comb(int m,int n){\n if(m==0||m==n)return 1;\n else return fac[n]*invfac[m]%P*invfac[n-m]%P;\n }\n pair<int,ll> dfs(Tree* t){\n if(!t)return {0,1};\n int sl,sr;\n ll wl,wr;\n tie(sl,wl)=dfs(t->l);\n tie(sr,wr)=dfs(t->r);\n ll w=(wl*wr%P)*comb(sl,sl+sr)%P;\n return {sl+sr+1,w};\n }\npublic:\n int numOfWays(vector<int>& nums) {\n fac.push_back(1);\n invfac.push_back(1);\n for(int i=1;i<=nums.size();i++){\n fac.push_back(fac.back()*i%P);\n invfac.push_back(inv(fac.back()));\n }\n map<int,Tree*> mp;\n Tree* root=new Tree(nums[0]);\n mp[nums[0]]=root;\n for(int i=1;i<nums.size();i++)\n insert(mp,nums[i]);\n return (dfs(root).second+P-1)%P;\n }\n};\n``` | 4 | 0 | [] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | [Python3] math-ish | python3-math-ish-by-ye15-q7ci | \n\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \n def fn(nums): \n """Post-order traversal."""\n if | ye15 | NORMAL | 2020-08-30T04:09:36.695102+00:00 | 2020-08-30T04:09:36.695133+00:00 | 757 | false | \n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \n def fn(nums): \n """Post-order traversal."""\n if len(nums) <= 1: return len(nums) # boundary condition \n ll = [x for x in nums if x < nums[0]]\n rr = [x for x in nums if x > nums[0]]\n left, right = fn(ll), fn(rr)\n if not left or not right: return left or right\n ans = comb(len(rr)+len(ll), len(rr))\n return ans*left*right\n \n return (fn(nums)-1) % 1_000_000_007\n``` | 4 | 1 | ['Python3'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Java || 7ms || DFS with Pascal's Triangle | java-7ms-dfs-with-pascals-triangle-by-du-6a0v | \nclass Solution {\n // Pascal\'s Triangle is built only once per SUBMIT, and then can be \n // used for all other test cases of the SUBMIT.\n private | dudeandcat | NORMAL | 2023-06-16T14:41:56.716292+00:00 | 2023-08-26T19:04:29.920167+00:00 | 280 | false | ```\nclass Solution {\n // Pascal\'s Triangle is built only once per SUBMIT, and then can be \n // used for all other test cases of the SUBMIT.\n private static int[][] pascalsTriangle = createPascalsTriangle(1001);\n private static final int MOD = 1_000_000_007;\n\n \n // Main method called by leetcode.\n public int numOfWays(int[] nums) {\n return dfs(nums, nums.length) - 1;\n }\n\n \n // Use an array representing a root followed by the values below that root, \n // to calculate the number of combinations, by recursively breaking the \n // array into smaller tree problems.\n private int dfs(int[] nums, int n) {\n if (n <= 2) return 1;\n final int[] left = new int[n - 1];\n final int[] right = new int[n - 1];\n final int rootVal = nums[0];\n int leftIdx = 0;\n int rightIdx = 0;\n for (int i = 1; i < n; i++) \n if (nums[i] < rootVal) \n left[leftIdx++] = nums[i];\n else\n right[rightIdx++] = nums[i];\n return (int)(((((long)dfs(left, leftIdx) * dfs(right, rightIdx)) % MOD) * \n pascalsTriangle[n - 1][leftIdx]) % MOD);\n }\n \n \n // Build table of Pascal\'s triangle values. Only have to build \n // it once per SUBMIT, then all test cases can use the same triangle.\n static private int[][] createPascalsTriangle(int maxN) {\n int[][] pt = new int[maxN][];\n for (int i = 0; i < maxN; i++) {\n pt[i] = new int[i + 1];\n pt[i][0] = pt[i][i] = 1;\n for (int j = 1; j < i; j++) \n pt[i][j] = (pt[i - 1][j - 1] + pt[i - 1][j]) % MOD;\n }\n return pt;\n }\n}\n```\n\n**--- Update: June 20, 2023 ---**\nSomeone has some code that runs at 4ms and uses a different algorithm. My code ran at 7ms. I like this faster code. It still uses the trick of creating a fixed value table only once per SUBMIT, then the other test cases can use that generated table. This code show a different and better method for initializing a fixed value table called `mults[]`, from the method used in the above code for `pascalsTriangle[][]`.\n```\nclass Solution {\n static final int MAX = 1000;\n\tstatic final int MOD = 1_000_000_007;\n\tstatic final TreeNode[] q = new TreeNode[MAX];\n\tstatic final long[] mults = new long[MAX + 1];\n\tstatic {\n\t\tmults[0] = 1;\n\t\tfor (int i = 1; i <= MAX; i++) \n\t\t\tmults[i] = (mults[i - 1] * i) % MOD;\n\t}\n\n\tpublic int numOfWays(int[] nums) {\n\t\tTreeNode root = new TreeNode(nums[0]);\n\t\tfor (int i = 1; i < nums.length; i++) {\n\t\t\troot.add(nums[i]);\n\t\t}\n\t\tint len = 0;\n\t\tq[len++] = root;\n\t\tlong d = 1;\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tfinal TreeNode node = q[i];\n\t\t\td = (d * node.count) % MOD;\n\t\t\tif (node.left != null)\n\t\t\t\tq[len++] = node.left;\n\t\t\tif (node.right != null)\n\t\t\t\tq[len++] = node.right;\n\t\t}\n\t\treturn (int) ((mults[len] * inverse(d) + MOD - 1) % MOD);\n\t}\n\n\tstatic long inverse(long y) {\n\t\tlong e = MOD - 2, a = 1;\n\t\twhile (e > 0) {\n\t\t\tif (e % 2 == 1) {\n\t\t\t\ta = (a * y) % MOD;\n\t\t\t}\n\t\t\te /= 2;\n\t\t\ty = (y * y) % MOD;\n\t\t}\n\t\treturn a;\n\t}\n\t\n\tstatic final class TreeNode {\n\t\tint val;\n\t\tint count;\n\n\t\tTreeNode left;\n\t\tTreeNode right;\n\n\t\tpublic TreeNode(int val) {\n\t\t\tthis.val = val;\n\t\t\tthis.count = 1;\n\t\t}\n\n\t\tvoid add(int val) {\n\t\t\tfor (TreeNode node = this;;) {\n\t\t\t\tnode.count++;\n\t\t\t\tfinal TreeNode next = val < node.val ? node.left : node.right;\n\t\t\t\tif (next == null) {\n\t\t\t\t\tif (val < node.val) {\n\t\t\t\t\t\tnode.left = new TreeNode(val);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnode.right = new TreeNode(val);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnode = next;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n``` | 3 | 0 | ['Java'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Rust | βi dont like treesβ faster-then-editorial approach | rust-i-dont-like-trees-faster-then-edito-z9gf | Intuition\nThe answer will be the product for all nodes of $\binom{k+m}{m}$ where $k$ and $m$ are sizes of left and right subtree of the node, respectively.\n\n | tifv | NORMAL | 2023-06-16T04:56:08.415159+00:00 | 2023-06-16T04:57:45.635517+00:00 | 251 | false | # Intuition\nThe answer will be the product for all nodes of $\\binom{k+m}{m}$ where $k$ and $m$ are sizes of left and right subtree of the node, respectively.\n\nWe want to compute the sizes of subtrees somehow. The easiest way would be to either build the tree directly or somehow iterate through it via function recursion.\n\nBut we are not going to do this for two reasons. First, we don\'t like trees. Second, this will take worst-case quadratic time (we are talking `[1, 2, 3, ..., 1000]` case here).\n\n(As evident from the editorial, a quadratic time solution will work. But we can to better than this.)\n\n# Approach\nInstead we can just reverse the permutation and notice the answer immediately. For any value $i$ in the reversed permutation, if we locate values $j$ and $k$ that are less than $i$ and are closest to $i$ from right and left respectively, i.e.\n$[\u2026, j, \\underbrace{\u2026}_{\\text{values}\u2265i}, i, \\underbrace{\u2026}_{\\text{values}\u2265i}, k, \u2026]$\nthen the values between $j$ and $i$ are the indices (in the original array) of values in the left subtree of $i$, and the values between $i$ and $k$ are the indices of values in the right subtree.\n\nTherefore we only need to reverse the permutation (which is essentially sorting the original array) and then have a pass though it noting for each value $i$ the distances to the closest values that are less than $i$ (this will need a stack of previous smaller values).\n\nAfter that only the problem of computing the binomial coefficients remains. Unlike editorial, which uses a quadratic solution by precomputing Pascal\'s triangle, we will use $\\binom{k+m}{m} = \\frac{(k+m)!}{k! \\cdot m!}$ formula, and only precompute the factorials. In fact, since factorials are constants, we can precompute them compile-time (up to $999!$) using Rust\'s const expressions.\n\n# Complexity\n- Time complexity: $O(n \\log(n))$, where $n = nums.\\mathrm{length}$.\n\n- Space complexity: $O(n)$.\n\nLeetCode shows `4 ms` and `2.3 MB`.\n\n# Code\n```\n/// Standard \u201Cgive the answer modulo 10\u2079\xA0+\xA07\u201D thing\nmod modulo {\n\nuse std::{ops::{Add, Sub, Mul, Div, AddAssign, MulAssign}, iter::Sum};\n\n#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub struct I32Mod(i32);\n\nfn ext_gcd(a: i32, b: i32) -> (i32, i32, i32) {\n let (mut a, mut b) = (a, b);\n let (mut ma, mut na, mut mb, mut nb) = (1_i32, 0_i32, 0_i32, 1_i32);\n assert!(a > 0 && b > 0);\n while b > 0 {\n let (k, r) = (a / b, a % b);\n let (mr, nr) = (\n ma - k * mb,\n na - k * nb,\n );\n a = b;\n ma = mb; na = nb;\n b = r;\n mb = mr; nb = nr;\n }\n return (a, ma, na);\n}\n\nimpl I32Mod {\n pub const MOD: i32 = 10_i32.pow(9) + 7;\n\n #[inline]\n pub fn inverse(self) -> Self {\n assert!(self.0 != 0, "only nonzero elements are inversible");\n let (d, _, n) = ext_gcd(Self::MOD, self.0);\n assert!(d == 1, "element should be inversible");\n return n.into()\n }\n\n pub const fn const_from(value: i32) -> Self {\n Self((value % Self::MOD + Self::MOD) % Self::MOD)\n }\n\n pub const fn const_mul(self, other: I32Mod) -> I32Mod {\n Self((\n (self.0 as i64 * other.0 as i64) % (Self::MOD as i64)\n ) as i32)\n }\n\n}\n\nimpl From<i32> for I32Mod {\n #[inline]\n fn from(value: i32) -> Self {\n Self((value % Self::MOD + Self::MOD) % Self::MOD)\n }\n}\n\nimpl From<I32Mod> for i32 {\n #[inline]\n fn from(value: I32Mod) -> i32 {\n value.0\n }\n}\n\nimpl Add<I32Mod> for I32Mod {\n type Output = I32Mod;\n #[inline]\n fn add(self, other: I32Mod) -> I32Mod {\n Self((self.0 + other.0) % Self::MOD)\n }\n}\n\nimpl Sub<I32Mod> for I32Mod {\n type Output = I32Mod;\n #[inline]\n fn sub(self, other: I32Mod) -> I32Mod {\n Self((self.0 - other.0 + Self::MOD) % Self::MOD)\n }\n}\n\nimpl Mul<I32Mod> for I32Mod {\n type Output = I32Mod;\n #[inline]\n fn mul(self, other: I32Mod) -> I32Mod {\n Self((\n (self.0 as i64 * other.0 as i64) % (Self::MOD as i64)\n ) as i32)\n }\n}\n\nimpl Div<I32Mod> for I32Mod {\n type Output = I32Mod;\n // #[inline]\n fn div(self, rhs: I32Mod) -> Self::Output {\n self * rhs.inverse()\n }\n}\n\nimpl AddAssign<I32Mod> for I32Mod {\n #[inline]\n fn add_assign(&mut self, other: I32Mod) {\n *self = *self + other;\n }\n}\n\nimpl MulAssign<I32Mod> for I32Mod {\n #[inline]\n fn mul_assign(&mut self, other: I32Mod) {\n *self = *self * other;\n }\n}\n\n} // mod modulo\n\nuse modulo::I32Mod;\n\nconst MAX_N: usize = 1000;\n\nconst factorials: [I32Mod; MAX_N] = { // compile-time precompute\n let mut result: [I32Mod; MAX_N] = [I32Mod::const_from(0); MAX_N];\n result[0] = I32Mod::const_from(1);\n let mut i = 1;\n while i < MAX_N {\n result[i] = result[i-1].const_mul(I32Mod::const_from(i as i32));\n i += 1;\n }\n result\n};\n\nimpl Solution {\n pub fn num_of_ways(nums: Vec<i32>) -> i32 {\n let n = nums.len();\n assert!(n <= MAX_N);\n let inv_nums = { // permutation inverse\n let mut inv_nums = (0..(n as i32)).collect::<Vec<_>>();\n inv_nums.sort_unstable_by_key(|&i| nums[i as usize]);\n inv_nums.push(-1); // add guard\n inv_nums\n };\n let margins = {\n let mut margins = Vec::<(i32,i32)>::with_capacity(n + 1);\n let mut stack = Vec::with_capacity(20);\n for (j, i) in inv_nums.into_iter().enumerate() {\n let j = j as i32;\n // clear the stack from values that are larger than us\n // (guard will wipe the stack on last iteration)\n loop { match stack.last() {\n Some(&(j1, i1)) if i1 > i => {\n margins[j1 as usize].1 = j - j1 - 1;\n stack.pop();\n },\n _ => break,\n } }\n margins.push((\n match stack.last() {\n Some(&(j1, _)) => j - j1 - 1,\n None => j,\n },\n -1, // must get overwritten later\n ));\n stack.push((j, i));\n }\n margins.pop(); // remove guard\n margins\n };\n let mut result_frac = (I32Mod::from(1), I32Mod::from(1));\n for (left, right) in margins {\n result_frac.0 *= factorials[(left + right) as usize];\n result_frac.1 *= factorials[left as usize];\n result_frac.1 *= factorials[right as usize];\n }\n return (result_frac.0 / result_frac.1 - 1.into()).into();\n }\n}\n```\n\nP.S. It\'s a joke. I like trees. Just not in this problem. | 3 | 0 | ['Rust'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | C# Solution because there weren't any others | c-solution-because-there-werent-any-othe-81ay | Approach\nGenerates a table of all binomial coefficients to reference, then calculates the number of combinations for all subtrees with recursion. \nSame as the | GOBurrito | NORMAL | 2023-06-16T03:52:44.792322+00:00 | 2023-06-16T03:54:46.663142+00:00 | 801 | false | # Approach\nGenerates a table of all binomial coefficients to reference, then calculates the number of combinations for all subtrees with recursion. \nSame as the editorial suggests.\n\nI first tried a solution calculating and caching factorials, but it was not fun trying to work with values as large as 35!\nThis one is better.\n\n# Code\n```\n public class Solution\n {\n readonly int mod = 1000000007; //% 10^9 + 7 is requirement of problem\n long[,] coefficientTable;\n public int NumOfWays(int[] nums)\n {\n GenerateBinomialCoefficientTable(nums.Length);\n return (NumOfWays(nums.ToList()) - 1) % mod;\n }\n public int NumOfWays(List<int> nums)\n {\n if (nums.Count <= 2)\n return 1;\n\n List<int> left = new List<int>();\n List<int> right = new List<int>();\n int root = nums[0];\n\n for (int i = 1; i < nums.Count; i++)\n {\n if (nums[i] < root)\n left.Add(nums[i]);\n else\n right.Add(nums[i]);\n }\n\n long waysLeft = NumOfWays(left);\n long waysRight = NumOfWays(right);\n long subtrees = (waysLeft * waysRight) % mod;\n long binomialCoefficient = coefficientTable[nums.Count - 1, left.Count];\n return (int)((binomialCoefficient * subtrees) % mod);\n }\n public void GenerateBinomialCoefficientTable(int size)\n {\n coefficientTable = new long[size, size];\n for (int i = 0; i < size; ++i)\n {\n coefficientTable[i, 0] = 1;\n coefficientTable[i, i] = 1;\n }\n for (int i = 2; i < size; i++) \n for (int j = 1; j < i; j++) \n coefficientTable[i, j] = (coefficientTable[i - 1, j - 1] + coefficientTable[i - 1, j]) % mod; \n }\n }\n``` | 3 | 0 | ['C#'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Python3 solution Fast With ExPlanation | python3-solution-fast-with-explanation-b-a9ta | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can approach the problem by using a recursive approach. \n# Approach\n Describe your | Obose | NORMAL | 2023-01-30T23:01:55.039455+00:00 | 2023-01-30T23:01:55.039487+00:00 | 977 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can approach the problem by using a recursive approach. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, we can use a recursive approach. We start from the first element of the array, and find the number of elements smaller and larger than the current node. We then make use of the combination formula to calculate the number of combinations with the current node. We then recursively call the same function for the left and right subarrays, and multiply the results together. Finally, we subtract one and take the modulo of the result with 10^9 + 7 to get our final answer. \n\n```\ndef comb(n, r):\n return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))\n```\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n def dfs(nums):\n if len(nums) <= 2: return 1\n left = [n for n in nums if n < nums[0]]\n right = [n for n in nums if n > nums[0]]\n return comb(len(nums) - 1, len(left)) * dfs(left) * dfs(right)\n return (dfs(nums) - 1) % (10 ** 9 + 7)\n``` | 3 | 0 | ['Array', 'Math', 'Divide and Conquer', 'Dynamic Programming', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Detailed Explanation | (Hopefully) Easy to understand | Python Solution | detailed-explanation-hopefully-easy-to-u-n5sl | Intuition and Approach\n Describe your first thoughts on how to solve this problem. \nLet\'s start small\n\nLook at this Binary Search Tree\n\n 2\n / \\\n 1 | with_love_kd | NORMAL | 2023-01-28T13:25:56.204712+00:00 | 2023-01-28T13:25:56.204846+00:00 | 183 | false | # Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet\'s start small\n\nLook at this Binary Search Tree\n```\n 2\n / \\\n 1 3\n```\nWhat do you think is the valid array to form this BST?\n`[2,1,3]` and `[2,3,1]` both are correct here.\n\nLet\'s look at another BST\n```\n 6\n / \\\n 5 7\n```\nWhat do you think is the valid array to form this tree?\nI guess, you got it right - `[6,5,7]` and `[6,7,5]`.\n\nWhat **observations** have you concluded from the above two examples?(I strongly suggest you to think, before you move ahead)\n-> The **root** is always **first** (This is our **Observation #1**)\n-> Also, if nodes are on the same level, their relative ordering does not matter (**Obs #2**)\n\nLet\'s take a look at a bigger BST\n```\n 4 \n / \\\n 2 6\n / \\ / \\\n 1 3 5 7\n```\nWhat do you think is the valid array to form this tree?\n\nThis Might look difficult at first. But if we properly **observe**, we can use the above two examples to get some solution here.\n\nUsing Observation #1, 4 will be the first element.\n\nLet\'s break down the problem to left and right subtree. Since, it is a BST all the elements smaller than root will be on the left subtree and vice versa.\n\nUsing Obs #2, the relative order of `1,3,5,7` won\'t matter. But from Obs #1, `1,3` has to be **after** `2` and `5,7` has to be **after** `6`. And similarly, the relative order of `2` and `6` won\'t matter.\n\nSo, how do we get the permutations of subtrees?\n\n****\n**Before moving down further, I highly encourage to solve these Problems first to get the grasp of what is coming ahead:**\n1. [Permutations](https://leetcode.com/problems/permutations/description/)\n2. [Permutations II](https://leetcode.com/problems/permutations-ii/)\n3. [Permutations of a String](https://leetcode.com/problems/permutation-in-string/description/) (Optional)\n****\n\n$$Continuing....$$\nSo, how do we get the permutations of subtrees?\nTo tackle this problem let\'s mark left subtree nodes as **0** and right subtree nodes as **1**. Because with that, the relative ordering of the subtree will stay the same.\n\nFor example, `[2,1,3,6,5,7]` = `[0,0,0,1,1,1]`. Now if we generate different permutations of this, let\'s say `[1,0,1,0,1,0]`, we can unmark zeros and ones with the respective subtree values i.e., `[6,2,5,1,7,5]`. Observe that the relative order of subtree nodes remains intact.\n\nNow, the permutation [6,2,5,**1**,7,**5**] and [6,2,5,**5**,7,**1**] (Obeserve postiion of `1` and `5`) both are correct, but since we repalce them with **0s** and **1s** both of them are considered same only. To get that value, we follow the same process on the subtree as well i.e.,\n`[1,5]` = `[0,1]` (left subtree as **0** and right as **1**). Which generates 2 permutations.\n\nThis part -- `[2,1,3,6,5,7]` = `[0,0,0,1,1,1]` -- will generate `(6!/(3! * 3!))` permutations (For proof - You can try this on a smaller number say, `[0,0,1,1]`). \n\nWell, how is the above formula concluded? You can think of it as chosing 3 places from 6 available places (`6 C 3`) (Or formula of permutations having duplicate values). Also, to note that we also have to get the permutations of the subtree, so we multiply it with permutations of subtrees.\n\nSo, it will become `(6!/(3! * 3!)) * 2! * 2!` (`2!` for left and `2!` for permutations of right subtree)\n\nHence, we keep on doing the same recursively for all subtrees and multiply their corresponding permutations.\n\n# Code\n```\nclass Solution:\n def numOfWays(self, numList: List[int]) -> int:\n def find_no_of_combinations_of(nums):\n # having a single num has just 1! permutations\n if len(nums) < 2:\n return 1\n # get the left subtree\n left_subtree = [num for num in nums if num < nums[0]] \n # get the right subtree\n right_subtree = [num for num in nums if num > nums[0]]\n \n # The (6!/ (3! * 3!)) * 2! * 2! step\n return (comb(len(left_subtree) + len(right_subtree), len(left_subtree)) *\\\n find_no_of_combinations_of(left_subtree) *\\\n find_no_of_combinations_of(right_subtree)) % (10**9 + 7)\n \n # at last we minus 1 because our ans permutations \n # has the permutation from the question as well\n return find_no_of_combinations_of(numList) - 1\n\n \n``` | 3 | 0 | ['Binary Search Tree', 'Combinatorics', 'Binary Tree', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ | Math | Combination Theory | Dynamic Programming | c-math-combination-theory-dynamic-progra-sow8 | 1569. Number of Ways to Reorder Array to Get Same BST\n\nIt\'s a interesting math problem. \n\nWe will solve this problem by recursion, it\'s a little similar t | sinkinben | NORMAL | 2021-12-27T13:59:40.147238+00:00 | 2021-12-28T03:26:43.602405+00:00 | 576 | false | **1569. Number of Ways to Reorder Array to Get Same BST**\n\nIt\'s a interesting math problem. \n\nWe will solve this problem by recursion, it\'s a little similar to dynamic programming.\n\n+ On the top level, there is no doubt that `nums[0]` is the root of BST.\n+ Remind that in BST, we have `left < root < right`.\n+ Thus, those numbers who are smaller than `nums[0]`, we put them in the vector `left` (which are the left children). And the others who greater than `nums[0]`, we put them in vector `right` (which are the right children).\n+ There are `n` position, index-0 is occupied by `nums[0]`. And we should put `left` in the remained `n-1` positions, there are `C[n-1][k]` cases, where `k` is the length of `left`.\n > Remind the combination formula:\n > `C[n][k] = C[n-1][k] + C[n-1][k-1]`\n\n+ Let `f(nums)` denote the number of cases, if we get the `left, right` vector mentioned above, then we can have:\n```cpp\nf(nums) = f(left) * f(right) * C[n - 1][k]\n```\nwhere `k` is the length of `left` vector, and `n` is the length of vector `nums`.\n\n```cpp\nclass Solution {\npublic:\n const int mod = (int)(1e9) + 7;\n vector<vector<int>> C;\n int numOfWays(vector<int>& nums) \n {\n int n = nums.size();\n C.resize(n, vector<int>(n, 0));\n for (int i = 0; i < n; ++i)\n {\n C[i][0] = 1;\n for (int j = 1; j <= i; ++j)\n C[i][j] = (C[i-1][j] + C[i-1][j-1]) % mod;\n }\n return f(nums) % mod - 1;\n }\n \n int64_t f(vector<int> &nums)\n {\n int n = nums.size();\n if (n <= 1) return 1;\n vector<int> left, right;\n for (int i = 1; i < n; ++i)\n {\n if (nums[i] > nums[0]) right.emplace_back(nums[i]);\n else left.emplace_back(nums[i]);\n }\n int64_t lval = f(left) % mod, rval = f(right) % mod;\n return ((C[n - 1][left.size()] * lval) % mod * rval) % mod;\n }\n};\n```\n\nThis solution is slow, but it can work :-D !\n | 3 | 0 | ['Combinatorics'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Python3 original counting and if we want to print all bst list | python3-original-counting-and-if-we-want-mb3v | \nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \n # Time O(N^2)\n # Space O(N) for recursion stack\n \n | walkon302 | NORMAL | 2021-08-27T18:21:40.769039+00:00 | 2021-08-27T18:21:40.769090+00:00 | 1,362 | false | ```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \n # Time O(N^2)\n # Space O(N) for recursion stack\n \n def combine(n, k):\n \n def fac(n):\n s = 1\n for i in range(1, n + 1):\n s *= i\n return s\n \n return fac(n) // (fac(n - k) * fac(k))\n \n \n def recur(nums):\n if len(nums) <= 2: \n return 1\n left = []\n right = []\n for n in nums[1:]:\n if n < nums[0]:\n left.append(n)\n elif n > nums[0]:\n right.append(n)\n curr = combine(len(left)+len(right), len(right))\n return curr * recur(left) * recur(right)\n \n return (recur(nums)-1) % (10**9+7)\n \n """\n print all bst\n # Time O(2^N)\n # Space O(2^N)\n def get_all_bst(nums):\n candidates = []\n \n def recur(l, li, r, ri, temp):\n nonlocal candidates\n \n if len(temp) == len(l) + len(r):\n candidates.append(temp[:])\n return\n if li < len(l):\n temp.append(l[li])\n recur(l, li+1, r, ri, temp)\n temp.pop()\n if ri < len(r):\n temp.append(r[ri])\n recur(l, li, r, ri+1, temp)\n temp.pop()\n \n start = nums[0]\n left = [v for v in nums if v < start]\n right = [v for v in nums if v > start]\n recur(left, 0, right, 0, [])\n res = []\n for candidate in candidates:\n r = [start] + candidate\n if r != nums:\n res.append(r)\n \n return res\n """\n``` | 3 | 0 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | No pascal's triangle or yang or combinatoral formula. Simple dp accepted and faster than 60% | no-pascals-triangle-or-yang-or-combinato-5g2m | 1) For the given list, 1st number is the root. Make a list of smaller and bigger numbers after this. And do the following recursively for each of them.\n2) We n | vivek_bansal | NORMAL | 2020-09-07T10:57:13.974626+00:00 | 2020-09-07T10:57:13.974678+00:00 | 304 | false | 1) For the given list, 1st number is the root. Make a list of smaller and bigger numbers after this. And do the following recursively for each of them.\n2) We need to merge bigger and smaller list together in a way that relative ordering of the number is maintained.\n```\n\'\'\'\nAssume dp[i][j] as the number of ways to put two lists of length i and j together while preserving relative order. Then you can either pick 1 element of i or 1 element of j. Therefore: \n\'\'\'\ndp[i][j] = dp[i-1][j] + dp[i][j-1]\ndp[0][x] = 1\ndp[x][0] = 1\n```\n\n\n```\nclass Solution:\n \n def finddp(self, m, n):\n dp = [[0 for j in range(n+1)] for i in range(m+1)]\n for i in range(m+1):\n dp[i][0] = 1\n \n for j in range(n+1):\n dp[0][j] = 1\n \n \n for i in range(1, m+1):\n for j in range(1, n+1):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n return dp\n \n \n \n def numOfW(self, nums: List[int], dp) -> int:\n if len(nums) == 0:\n return 1\n bigger = []\n smaller = []\n for n in nums[1:]:\n if n > nums[0]:\n bigger.append(n)\n elif n < nums[0]:\n smaller.append(n)\n \n ans = dp[len(bigger)][len(smaller)]\n x = 1\n if len(bigger):\n x = self.numOfW(bigger, dp)\n \n if len(smaller):\n x *= self.numOfW(smaller, dp)\n \n ans = ans * x\n return ans\n \n def numOfWays(self, nums: List[int]) -> int:\n x = self.finddp(len(nums), len(nums))\n return self.numOfW(nums, x) % (10**9 + 7) - 1\n``` | 3 | 2 | [] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | Python short DP | python-short-dp-by-hjscoder-w91q | Explanation: \nI used recursive + dp to solve this problem. \nIf there is regulation by not using any library to generate Permutation Count, DP can come to he | hjscoder | NORMAL | 2020-08-30T23:15:32.568704+00:00 | 2020-08-30T23:25:41.944105+00:00 | 472 | false | <h4> Explanation: </h4>\nI used recursive + dp to solve this problem. \nIf there is regulation by not using any library to generate Permutation Count, DP can come to help to get the Permutation Count. Here is the code:\n\n\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n dp = [[1 for r in range(len(nums)+1)] for l in range(len(nums)+1)]\n \n for i in range(1, len(nums)):\n for j in range(1, len(nums)):\n dp[i][j] = (dp[i][j-1] + dp[i-1][j])\n \n return (self.getNum(nums, dp) - 1)%(10**9+7)\n \n def getNum(self, nums, dp):\n if len(nums) <= 2:\n return 1\n left, right = [num for num in nums if num < nums[0]], [num for num in nums if num > nums[0]]\n return (self.getNum(left, dp)*dp[len(left)][len(right)]*self.getNum(right, dp))\n``` | 3 | 0 | [] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | [Python3] Divide and Conquer | detailed explanation | python3-divide-and-conquer-detailed-expl-6pxf | The idea is divide and conquer:\n1) To get the same BST, we must first insert the root(the first element in the array), then we can insert its left subtree and | xuanyuchen0 | NORMAL | 2020-08-30T14:44:09.031966+00:00 | 2020-09-01T05:15:38.414921+00:00 | 298 | false | The idea is divide and conquer:\n1) To get the same BST, we must first insert the root(the first element in the array), then we can insert its left subtree and right subtree.\n\n2) For both subtrees, we need to first insert root as well;\n\n3) when we have numbers of ways to arrange left subtree and right subtree, we only have to calculate the number of ways to arrange them into one array that does not change both subarrays\' original relative order within its elements.\n\nFor example, \n\n`nums = [3, 4, 5, 1, 2]`, `total_length` for both subtrees elements is `4`.\n\nFor left subtree, lnum = 1, only 1 arrangement: `[1, 2]`, `left_length = 2`\n\nFor right subtree, rnum = 1, only 1 arrangement: `[4, 5]`, `right_length = 2`\n\nThus, the total number of arrangements when put into one array should be equal to number of ways to take `left_length` positions out of `total_length`, which is `combinations(total_length, left_length)`. Here, we have `combinations(4, 2) = 6`, and the arrangements are:\n\n`[1,2,4,5]`\n\n`[1,4,2,5]`\n\n`[1,4,5,2]`\n\n`[4,1,2,5]`\n\n`[4,1,5,2]`\n\n`[4,5,1,2]`\n\nAlso, both subtrees could have more valid arragements, thus, the recurrence equation should be:\n\n`num(A) = num(left_subtree) * num(right_subtree) * combinations(total_length, left_length)`.\n\nFinally, we need to `-1` because the input array should not be counted.\n\n```\nclass Solution:\n def numOfWays(self, A: List[int]) -> int:\n mod =10 ** 9 + 7\n \n def split(left, right):\n lnum, rnum = 1, 1\n if left:\n lroot = left[0]\n lnum = split([l for l in left if l < lroot], [r for r in left if r > lroot])\n if right:\n rroot = right[0]\n rnum = split([l for l in right if l < rroot], [r for r in right if r > rroot])\n return lnum * rnum * comb(len(left) + len(right), len(left))\n \n root = A[0]\n return split([l for l in A if l < root], [r for r in A if r > root]) % mod - 1\n```\n\nTime: `O(nlogn)`, similar to quick sort, each time we call `split`, we choose the the first element to be the pivot and split the input array to be two subarrays(one contains all the elements less than pivot, the other one contains all the elements larger than pivot).\nSpace: `O(nlogn)`. | 3 | 0 | [] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Easiest Solution!!! | bests 78% of the java coders | | easiest-solution-bests-78-of-the-java-co-6nsc | Intuition\nThe intuition behind this code is to use a recursive approach to count the number of ways to split a list of numbers into two non-empty sublists, suc | maheshkumarofficial | NORMAL | 2023-11-11T01:07:01.151868+00:00 | 2023-11-11T01:07:01.151889+00:00 | 68 | false | # Intuition\nThe intuition behind this code is to use a recursive approach to count the number of ways to split a list of numbers into two non-empty sublists, such that the root of the tree is the largest number in the left sublist and the smallest number in the right sublist.\n\nWe can do this by first finding the root of the tree, which is the largest number in the left sublist. Then, we can split the list into two sublists based on whether the numbers are less than or greater than the root. We can then recursively count the number of ways to split each sublist into two non-empty sublists.\n# Approach\nFind the root of the tree, which is the largest number in the left sublist.\n\nSplit the list into two sublists based on whether the numbers are less than or greater than the root.\n\nRecursively count the number of ways to split each sublist into two non-empty sublists.\n\nMultiply the number of ways to split the left sublist by the number of ways to split the right sublist.\n\nReturn the product.\n\n# Complexity\n- Time complexity:\nThe time complexity of this code is O(2^n), where n is the number of nodes in the tree. This is because the recursive algorithm will call itself 2^n times, once for each possible split of the list into two non-empty sublists.\n\n\n- Space complexity:\nThe space complexity of this code is O(n), where n is the number of nodes in the tree. This is because the recursive algorithm will need to store a stack of frames, one for each recursive call.\n\n\n# Code\n```\nclass Solution {\n private static final int MOD = 1000000007;\n public int numOfWays(int[] nums) {\n List<Integer> list = new ArrayList<>();\n for (int num : nums) {\n list.add(num);\n }\n return countWays(list) - 1;\n }\n private int countWays(List<Integer> nums) {\n if (nums.size() <= 2) {\n return 1;\n }\n \n List<Integer> left = new ArrayList<>();\n List<Integer> right = new ArrayList<>();\n int root = nums.get(0);\n \n for (int i = 1; i < nums.size(); i++) {\n if (nums.get(i) < root) {\n left.add(nums.get(i));\n } else {\n right.add(nums.get(i));\n }\n }\n \n long leftCount = countWays(left);\n long rightCount = countWays(right);\n \n return (int) ((comb(nums.size() - 1, left.size()) % MOD) * (leftCount % MOD) % MOD * (rightCount % MOD) % MOD);\n }\n \n private long comb(int n, int k) {\n long[][] dp = new long[n + 1][k + 1];\n for (int i = 0; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= Math.min(i, k); j++) {\n dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % MOD;\n }\n }\n return dp[n][k];\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | EXPLAINED | Beginer friendly | Recursion | C++ | 90% FAST | O(n^2) | explained-beginer-friendly-recursion-c-9-7jlx | Intuition\n Describe your first thoughts on how to solve this problem. \n\nIf you are not familiar with how to form a BST form the array, you should definitely | joshuamahadevan1 | NORMAL | 2023-06-17T05:02:51.564370+00:00 | 2023-06-17T05:22:10.572565+00:00 | 551 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIf you are not familiar with how to form a BST form the array, you should definitely check it out online. [resource link](https://devcamp.com/trails/development-soft-skills/campsites/understanding-algorithms/guides/how-to-create-binary-search-tree-array) - idk if this is the best, but this looks good enough to establish a basic understanding.\n\nNext, we have to observe that arrays which satisfy topological ordering of the input array will produce the same tree. In other words, for the tree produced, there can be multiple valid topological sorts. All there arrays will still produce the same tree.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\nI have implemented the idea given in [this](https://codeforces.com/blog/entry/75627) blog post in code forces. It basically tells us that for a tree, the first element of the topological sort is gonna be the node itself. Next, we need to look at the topological sort of the left and right subtrees ( you can see the recursion forming now... ). When creating the rest of the topological sort for the currennt node, we need to preserve the ordering among the elements of these two lists.\n\nLet us say the n1, n2 are the length of the topological sorts of each subtree (which is also the number of nodes in the subtree), and t1, t2 be the number of topological sorts possible for each subtree. \n\nThe remaining part of the topo-sort should be n1+n2 long. First we select n1 positions from n1+n2 positions, which is (n1+n2)C(n1) number of ways. Now these n1 positions can be filled in t1 ways, and the remaining n2 positinos in t2 ways, resulting in the number of topo sorts for current node to be **(n1+n2)C(n1) * t1 * t2**. The number of nodes in the subtree naturally is **n1+n2+1**\n\n# Complexity\n- Time complexity: O(n^2) - Creating BST\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(n) - facts array to store factorials\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nPlease upvote the solutions if you find it helpful :)\n# Code\n```\nclass Solution {\n struct BSTNode{\n int val;\n BSTNode *left, *right;\n \n BSTNode( int x ) {\n val = x;\n left = NULL, right = NULL;\n }\n };\n\n void insert_into_BST( int val, BSTNode* root ) {\n BSTNode* prev = NULL;\n\n while( root ) {\n prev = root;\n if( val > root->val ) root = root->right;\n else root = root->left;\n }\n\n if( val > prev->val ) prev->right = new BSTNode( val );\n else prev->left = new BSTNode( val );\n }\n\n const int mod = 1e9+7;\n vector<long long> facts;\n\n pair<int,long long> solve( BSTNode* curr ) {\n if( curr==NULL ) return {0,1};\n\n auto [n1, t1] = solve( curr->left );\n auto [n2, t2] = solve( curr->right );\n\n t1 = (t1*t2) % mod;\n return { n1+n2+1, (t1*comb(n1+n2, n1))%mod };\n }\n\n int comb( int n, int r ) {\n long long num = facts[n],\n denom = ( facts[n-r] * facts[r] ) % mod;\n\n // when p is prime, a^-1 mod p = a^p-2 mod p\n long long inv = fast_exponent( denom, mod-2 );\n\n return (num*inv)%mod;\n }\n\n long long fast_exponent( long long base, int exp ) {\n if( exp==0 ) return 1;\n if( exp%2==0 ) {\n long long t = fast_exponent( base, exp/2 );\n return (t*t)%mod;\n }\n return (fast_exponent(base, exp-1 )*base) % mod;\n } \npublic:\n int numOfWays(vector<int>& nums) {\n int n = nums.size();\n BSTNode* root = new BSTNode( nums[0] );\n\n facts.resize(n+1);\n facts[0]=1;\n for( int i=1; i<=n; i++ ) facts[i] = (i*facts[i-1])%mod;\n\n for( int i=1; i<n; i++ ) insert_into_BST( nums[i], root );\n\n return solve( root ).second-1;\n }\n};\n``` | 2 | 0 | ['C++'] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | [Python 3] Recursion, comb, beats 95+% | python-3-recursion-comb-beats-95-by-patr-riy2 | Intuition\nThe first idea I had here was that each root has to come before any of its children in the list, otherwise the tree will be out of order. This then m | patrickpeng168 | NORMAL | 2023-06-16T20:36:27.917333+00:00 | 2023-06-16T20:36:27.917364+00:00 | 58 | false | # Intuition\nThe first idea I had here was that each root has to come before any of its children in the list, otherwise the tree will be out of order. This then made me think of splitting the problem into subtrees (recursion). For each tree, the total number of combinations possible is the number of ways to shuffle its child subtrees directly, then multiplied by the number of ways to shuffle each child subtree.\n\nFor more clarity, in the example `[3,4,5,1,2]`, we can obtain `[3,1,4,5,2]` by shuffling directly, and then we note that we cannot shuffle the individual subtrees `[4,5]` or `[1,2]` further.\n\n# Approach\nThe recursion is not too complex once we have the idea. The base case here is a tree with two or less nodes (only one way to order the elements). \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is $$O(n^2)$$; each recursive layer requires an iteration through a linear array (pretty much.)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is also $$O(n^2)$$.\n\n# Code\n```\nfrom math import comb\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n # each root must come before any of its children\n # recursive call on each root given nodes in subtree\n # for each tree - total number of nodes - 1 choose the number of nodes in one subtree\n # multiply by the result for both subtrees\n\n def recurse(nodes):\n if len(nodes) <= 2:\n return 1\n else:\n l = []\n r = []\n for val in nodes[1:]:\n if val > nodes[0]:\n r.append(val)\n else:\n l.append(val)\n # comb calculates nCk\n return comb(len(nodes) - 1, len(l)) * recurse(l) * recurse(r)\n\n return (recurse(nums) - 1) % 1000000007\n``` | 2 | 0 | ['Recursion', 'Python3'] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | The World Needs Another Python Solution | the-world-needs-another-python-solution-99cwt | Approach\n\nWe use recursion. The steps below explain the solution.\n\n1. The root must be inserted first.\n2. The order of nodes inserted in the left subtree i | trentono | NORMAL | 2023-06-16T20:21:34.202318+00:00 | 2023-06-17T16:05:21.108315+00:00 | 65 | false | # Approach\n\nWe use recursion. The steps below explain the solution.\n\n1. The root must be inserted first.\n2. The order of nodes inserted in the left subtree is independent of the order of nodes inserted in the right subtree.\n3. The nodes in the left subtree can be inserted in any order relative to the nodes in the right subtree.\n4. The recursive relationship is therefore \n`f(nums) = f(left subtree nodes list)*f(right subtree nodes list)*C(len(left subtree)+len(right subtree), len(left subtree))`\nwhere C(n, k) is the binomial coefficient, also called "n choose k". In this expression, the product `f(left subtree nodes list)*f(right subtree nodes list)` comes from observation (2), and the binomial coefficient `C(len(left subtree)+len(right subtree), len(left subtree))` comes from observation (3).\n5. The base case is f([]) == 1.\n6. Since we\'re returning the number of ways of reordering the list, we need to exclude the present ordering. This means we need to subtract 1 from the final result. The need to subtract 1 at the end is also the only reason why we need to define a separate function inside of our function body to perform the recursion. (We don\'t want to subtract 1 on recursive calls.)\n7. Don\'t forget to give the result modulo 10**9 + 7.\n\n# Complexity\n- Time and space complexity are both O(n^2) in the worst case, O(n*log(n)) in the average case.\n- The worst case occurs when the list is mostly sorted.\n\n# Code\n```\nfrom math import comb\n\nB = 10**9 + 7\n\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n def f(nums):\n if len(nums) == 0:\n return 1\n \n left = [n for n in nums if n < nums[0]]\n right = [n for n in nums if n > nums[0]]\n\n return f(left)*f(right)*comb(len(left) + len(right), len(left)) % B\n\n return (f(nums)-1) % B\n``` | 2 | 0 | ['Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | [Java][Python] 2 Approch|| Faster than 96.8% Using Pascal's Tringle in java and combinatories , BST | javapython-2-approch-faster-than-968-usi-qc3d | Intuition\n Describe your first thoughts on how to solve this problem. \n- Intuition for Java:(using Pascal\'s Tringle)\nwe uses a recursive approach combined w | Anamika_aca | NORMAL | 2023-06-16T18:38:42.066667+00:00 | 2023-06-16T18:38:42.066685+00:00 | 189 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- **Intuition for Java:(using Pascal\'s Tringle)**\nwe uses a recursive approach combined with the Pascal\'s Triangle to calculate the number of ways to arrange the elements in the input array. It separates the elements into two sublists based on their values and recursively calculates the number of ways for each sublist. The final result is obtained by multiplying the number of ways for the sublists and the corresponding combination from the Pascal\'s Triangle.\n\n- **Intuition for Python:(by recursively)**\nWe uses a recursive approach to calculate the number of ways to arrange the elements in the input array. It separates the elements into two sublists based on their values and then recursively calculates the number of ways for each sublist. The final result is obtained by multiplying the number of ways for the sublists and the appropriate combination value.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Approach for Java-using Pascal\'s Tringle:**\n\nThe code defines a Solution class that contains the necessary methods and variables.\n\nThe code initializes a constant MOD with the value 1000000007. This constant is used to perform modulo arithmetic.\n\nThe code initializes a constant 2D array pascal_triangle using the BuildPascalsTriangle function. This array stores the Pascal\'s Triangle up to a size of 1000. Each element of the array represents the combination of choosing j elements from a set of i elements.\n\nThe numOfWays method takes an input array nums and converts it to a list. It then calls the NumsOfWays method to calculate the number of ways to arrange the array.\n\nThe NumsOfWays method recursively calculates the number of ways to arrange the elements in the input list nums. It first checks if the size of nums is less than or equal to 2. If so, it returns 1 since there is only one way to arrange 0 or 1 elements.\n\nIf nums has more than 2 elements, the method separates the elements into two lists: leftNodes and rightNodes. The leftNodes list contains elements smaller than the first element (root), and the rightNodes list contains elements greater than the first element.\n\nThe method recursively calls NumsOfWays on leftNodes and rightNodes to calculate the number of ways to arrange the elements in each sublist.\n\nThe method uses the formula: (NumsOfWays(leftNodes) * NumsOfWays(rightNodes) * pascal_triangle[n-1][leftNodes.size()]) % MOD to calculate the total number of ways to arrange the elements in nums. It multiplies the number of ways to arrange the left sublist by the number of ways to arrange the right sublist, and multiplies the result by the corresponding combination from the Pascal\'s Triangle.\n\nFinally, the method returns the calculated number of ways modulo MOD.\n\nThe BuildPascalsTriangle method constructs the Pascal\'s Triangle as a 2D array. It initializes the edges of the triangle with 1, and then fills in the remaining elements using the formula: pascal_triangle[i][j] = (pascal_triangle[i-1][j] + pascal_triangle[i-1][j-1]) % MOD.\n\n- **Approch for Python:**\n\nThe code defines a Solution class that contains the necessary methods and variables.\n\nThe code initializes a variable mod with the value 10 ** 9 + 7. This variable is used to perform modulo arithmetic.\n\nThe code defines a helper function combination(nl, nr) that calculates the combination of choosing nr elements from a set of nl + nr elements. It uses a precalculated array factorial to efficiently compute the combination.\n\nThe code defines a recursive helper function ways(arr) that calculates the number of ways to arrange the elements in the input list arr.\n\nIf the length of arr is less than or equal to 2, there is only one way to arrange the elements, so the function returns 1.\n\nOtherwise, the function selects the first element of arr as the root. It then separates the remaining elements into two sublists: left (containing elements smaller than the root) and right (containing elements greater than the root).\n\nThe function recursively calls itself on left and right to calculate the number of ways to arrange the elements in each sublist.\n\nThe function multiplies the number of ways for left and right by the combination of choosing the appropriate number of elements from each sublist. This is done using the combination function.\n\nFinally, the function returns the product of the calculated number of ways for left and right, modulo mod.\n\nThe main function numOfWays initializes a variable n with the length of the input array nums.\n\nIt also initializes an array factorial with length n and fills it with factorial values from 1 to n. This array is used to efficiently calculate combinations in the combination function.\n\nThe function calls ways(nums) to calculate the number of ways to arrange the elements in nums and subtracts 1 from it.\n\nFinally, the function returns the result modulo mod.\n\n# Complexity\n- Time complexity:O(2^n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- **for java code**\n\nThe numOfWays method initially converts the nums array to a List<Integer>. This conversion takes O(n) time, where n is the size of the nums array.\n\nThe NumsOfWays method recursively splits the input list into two sublists, leftNodes and rightNodes. The size of each sublist can be at most n-1, where n is the size of the original list. The recursion continues until the sublist size becomes 2 or less. Therefore, the time complexity of the NumsOfWays method is O(2^n).\n\nThe BuildPascalsTriangle method constructs a 2D array of size n x n, where n is set to 1000. The nested loops iterate n times each, resulting in a time complexity of O(n^2), which can be considered constant as 1000 is a fixed value.\n\nOverall, the time complexity of the code is dominated by the NumsOfWays method, which is O(2^n).\n\n- **for python code**\nThe combination function calculates the factorial of the sum of two inputs and performs two divisions. This takes constant time, so its time complexity is O(1).\n\nThe ways function recursively calls itself for left and right sublists. The size of each sublist can be at most n-1, where n is the size of the original list. Therefore, the recurrence relation for the time complexity of the ways function can be expressed as T(n) = 2T(n-1) + O(1), where T(n) is the time complexity for an input of size n. By expanding the recursion, we can see that T(n) is exponential, specifically O(2^n).\n\nThe loop in the numOfWays method iterates n times to calculate the factorial array. Each iteration performs multiplication, so the time complexity of this loop is O(n).\n\nOverall, the time complexity of the code is dominated by the ways function, which is O(2^n).\n\n- Space complexity:O(2^n) for java / O(n^2) for python\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- **for java code**\nThe numOfWays method takes an input array nums of size n. It creates two additional lists, leftNodes and rightNodes, which can potentially store all n elements of nums. Therefore, the space complexity of the numOfWays method is O(n).\n\nThe BuildPascalsTriangle method creates a 2D array pascal_tringle of size n x n, where n is set to 1000. Hence, the space complexity of this method is O(n^2), which can be considered constant as 1000 is a fixed value.\n\nOverall, the space complexity of the code is O(n + n^2), which simplifies to O(n^2) as the dominant term.\n\n- **for python code**\nThe combination function takes constant space, so its space complexity is O(1).\n\nThe ways function recursively creates new lists for the left and right sublists. The maximum depth of recursion can be n, and at each recursion level, two new lists are created. Therefore, the space complexity of the ways function is O(2^n).\n\nThe numOfWays method creates the factorial array of size n. Hence, the space complexity for this array is O(n).\n\nOverall, the space complexity of the code is O(2^n) due to the ways function and O(n) for the factorial array, resulting in a total space complexity of O(2^n + n).\n\n\n# Code\n```Java []\nclass Solution {\n\n private static final long MOD = 1000000007;\n private static final long[][] pascal_tringle = BuildPascalsTriangle();\n\n public int numOfWays(int[] nums) {\n List<Integer> arr = Arrays.stream(nums).boxed().collect(Collectors.toList()) ;\n \n return (int)((NumsOfWays(arr)-1) % MOD);\n }\n\n private long NumsOfWays(List<Integer> nums) {\n int n = nums.size();\n if (n <= 2) return 1;\n\n List<Integer> leftNodes = new ArrayList<>();\n List<Integer> rightNodes = new ArrayList<>();\n\n int root = nums.get(0);\n for (int i=1; i<n; i++) {\n if (nums.get(i) < root) {\n leftNodes.add(nums.get(i));\n } else {\n rightNodes.add(nums.get(i));\n }\n }\n\n return (((NumsOfWays(leftNodes) % MOD * NumsOfWays(rightNodes) % MOD) % MOD) * \n pascal_tringle[n-1][leftNodes.size()]) % MOD;\n }\n\n private static long[][] BuildPascalsTriangle() {\n int n=1000;\n long[][] pascal_tringle = new long[n][n];\n\n for (int i=0; i<n; i++) {\n pascal_tringle[i][0] = pascal_tringle[i][i] = 1;\n }\n for (int i=2; i<n; i++) {\n for (int j=1; j<i; j++) {\n pascal_tringle[i][j] =\n (pascal_tringle[i-1][j] + pascal_tringle[i-1][j-1]) % MOD;\n }\n }\n return pascal_tringle;\n }\n}\n```\n```Python []\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n\n mod = 10 ** 9 + 7\n\n def combination(nl,nr):\n return factorial[nl+nr] // factorial[nl] // factorial[nr]\n\n\n def ways(arr):\n if len(arr)<=2:\n return 1\n\n root = arr[0]\n\n left = [num for num in arr if num < root ]\n right = [ num for num in arr if num > root]\n \n return ways(left) * ways(right) * combination(len(left), len(right))\n\n n = len(nums)\n factorial = [1] * (n)\n\n for i in range(1,n):\n factorial[i]= factorial[i-1] * i\n\n return (ways(nums)-1) % mod; \n\n```\n\n | 2 | 0 | ['Java', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Python short and clean. | python-short-and-clean-by-darshan-as-glhy | Approach\nTL;DR, Similar to Editorial solution.\n\n# Complexity\n- Time complexity: O(n ^ 2)\n\n- Space complexity: O(n ^ 2)\n\n# Code\npython\nclass Solution:\ | darshan-as | NORMAL | 2023-06-16T18:38:12.455493+00:00 | 2023-06-16T18:38:12.455514+00:00 | 314 | false | # Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/editorial/).\n\n# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\n# Code\n```python\nclass Solution:\n def numOfWays(self, nums: list[int]) -> int:\n M = 1_000_000_007\n\n def num_ways(bst: Sequence[int]) -> int:\n if len(bst) <= 2: return 1\n lefts, rights = [x for x in bst if x < bst[0]], [x for x in bst if x > bst[0]]\n return num_ways(lefts) * num_ways(rights) * comb(len(lefts) + len(rights), len(lefts)) % M\n \n return (num_ways(nums) - 1) % M\n\n\n``` | 2 | 0 | ['Divide and Conquer', 'Binary Search Tree', 'Combinatorics', 'Python', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | β
100% Fast | C++ | Easy to understand & clean approach| TC: O(N) π₯| BST & Factorial Precomputation | 100-fast-c-easy-to-understand-clean-appr-xam2 | Intuition\nPrecomputation of factorial of a number till 1000 is required.\nDeclare a global variable to keep the final answer(say ans).\n \nStep1: Create a bina | prabhash_iitp | NORMAL | 2023-06-16T18:00:16.947344+00:00 | 2023-07-05T12:25:14.162174+00:00 | 552 | false | # Intuition\nPrecomputation of factorial of a number till 1000 is required.\nDeclare a global variable to keep the final answer(say ans).\n \nStep1: Create a binary search tree.\nStep2: For every node, find the no of nodes in left subtree(say L) and no of nodes in right subtree(say R) then do **ans = ans* (L+R combination L);** //calculating the total number of permutations possible\nStep3: return ans-1 as the final result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPrecomputation of factorial of a number till 1000 is required.\nDeclare a global variable to keep the final answer(say ans).\n \nStep1: Create a binary search tree.\nStep2: For every node, find the no of nodes in left subtree(say L) and no of nodes in right subtree(say R) then do **ans = ans* (L+R combination L);** //calculating the total number of permutations possible\nStep3: return ans-1 as the final result.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N\\*h) to create a BST, where h is the maximum height of a tree\n# Code\n```\n\nclass Solution {\npublic:\n #define ll long long\n ll mod = 1e9+7;\n struct Node{\n int value;\n Node* left;\n Node* right;\n Node(int val){\n value = val;\n left = NULL;\n right = NULL;\n }\n };\n\n ll fact[1001];\n void precalc() {\n fact[0] = 1;\n for(ll i = 1; i < 1001; i++)\n fact[i] =(fact[i - 1]*i)%mod;\n // fact[i]=fact[i-1]*i;\n }\n\n ll inv(ll x) {\n return x <= 1 ? x : mod - (long long)(mod/x) * inv(mod % x) % mod;\n }\n \n ll mul(ll x, ll y) {\n return ((x%mod) * 1ll * (y%mod)) % mod;\n }\n\n ll divide(ll x, ll y) {\n return mul(x, inv(y));\n }\n\n void insertBST(Node* root,int val){\n if(root->value>val){\n if(root->left==NULL){\n root->left = new Node(val);\n }\n else{\n insertBST(root->left,val);\n }\n }\n else if(root->value<val){\n if(root->right==NULL){\n root->right = new Node(val);\n }\n else{\n insertBST(root->right,val);\n }\n }\n }\n \n void printBST(Node* root){\n if(root==NULL) return;\n printBST(root->left);\n cout<<root->value<<" ";\n printBST(root->right);\n }\n\n \n ll compute(ll left,ll right){\n if(left==0 or right == 0) return 1LL;\n return divide(fact[left+right],mul(fact[left],fact[right]));\n }\n\n ll ans = 1;\n ll calculatePermutations(Node* root){\n if(root==NULL){\n return 0;\n }\n\n ll left = calculatePermutations(root->left);\n ll right = calculatePermutations(root->right);\n ll pnc = compute(left,right)%mod;\n ans = mul(ans,pnc);\n return 1+left+right;\n }\n int numOfWays(vector<int>& nums) {\n Node* root = new Node(nums[0]);\n //create BST\n for(int i = 0;i<nums.size();i++){\n insertBST(root,nums[i]);\n }\n\n precalc(); //precalculating the factorial till 1000\n calculatePermutations(root);\n return ans - 1;\n }\n};\n``` | 2 | 0 | ['C++'] | 3 |
number-of-ways-to-reorder-array-to-get-same-bst | Finding topological sorts (clean code + explanation) | finding-topological-sorts-clean-code-exp-klag | Intuition\nThis problem can be rephrased as finding the number of ways to topological sort the BST. We are given one, which can be used to build a tree, and the | captainspongebob1 | NORMAL | 2023-06-16T11:57:38.534989+00:00 | 2023-06-16T12:03:21.184021+00:00 | 66 | false | # Intuition\nThis problem can be rephrased as finding the number of ways to topological sort the BST. We are given one, which can be used to build a tree, and the task is to find the rest.\n\n# Approach\nAfter building our tree, define a helper function `h(x)` that returns the number of topological sortings for the tree node `x`. If number of nodes in the subtree `x` is less than or equal to 1, then `h(x) = 1` (Base case).\n\nFor an arbitrary tree node, the goal is to work out how many ways there are of interleaving the topological sorts of the left and right subtrees. For the time being, lets assume that both the left and right subtrees have exactly one topological sort each, and lengths `m` and `n` respectively (like example 2 in the problem where `x` is the root). Assume these sequences are $l=(l_1, l_2, ..., l_m)$ and $r=(r_1, r_2, ..., r_n)$.\n\nWe know the total length of the ordering is $m + n$, and if we can figure out where all of the values from $l$ go, those for $r$ will fall out. In other words, we need to choose $m$ indices from $m + n$; therefore the answer is $\\frac{(m + n)!}{m! n!}$ (combination formula).\n\nWhen there are more than 1 topological sorts for each subtree, we have to multiply the above formula by the product of these values (since the orderings are independent of each other... different subtrees):\n$$ \\frac{(m +n)!}{m!n!}\\times h(x_{left}) \\times h(x_{right}) $$.\n\n# Code\n```\nclass Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n self.size = 1\n\n def insert(self, x):\n self.size += 1\n if x < self.val:\n if self.left: self.left.insert(x)\n else: self.left = Node(x)\n else:\n if self.right: self.right.insert(x)\n else: self.right = Node(x)\n\n\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n root = Node(nums[0])\n for i in range(1, len(nums)):\n # Insert\n root.insert(nums[i])\n\n # Return num topsorts\n def h(root):\n if not node or (not root.left and not root.right): return 1\n L = h(root.left)\n R = h(root.right)\n return math.comb(root.size - 1, root.left.size if root.left else 0) * L * R\n\n return (h(root) - 1) % 1_000_000_007\n\n```\n\n# References\n\n- https://cs.stackexchange.com/questions/12713/find-the-number-of-topological-sorts-in-a-tree\n- https://cs.stackexchange.com/questions/12713/find-the-number-of-topological-sorts-in-a-tree | 2 | 0 | ['Math', 'Tree', 'Recursion', 'Combinatorics', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Easiest Explanation | Hard --> Easy | codestorywithMIK | easiest-explanation-hard-easy-codestoryw-725z | YouTube video link - Number of Ways to Reorder Array to Get Same BST\nMy Github Treasure - Number of Ways to Reorder Array to Get Same BST\n\n\n\nclass Solution | mazhar_mik | NORMAL | 2023-06-16T10:28:55.253127+00:00 | 2023-06-16T10:28:55.253146+00:00 | 60 | false | YouTube video link - [Number of Ways to Reorder Array to Get Same BST](https://www.youtube.com/watch?v=YMe9Q2yZvBo)\nMy Github Treasure - [Number of Ways to Reorder Array to Get Same BST](https://github.com/MAZHARMIK/Interview_DS_Algo/blob/master/Mathematical/Number%20of%20Ways%20to%20Reorder%20Array%20to%20Get%20Same%20BST.cpp)\n\n\n```\nclass Solution {\npublic:\n typedef long long ll;\n ll MOD = 1e9 + 7;\n \n vector<vector<ll>> PT;\n \n int solve(vector<int>& nums) {\n int m = nums.size();\n \n if(m < 3)\n return 1;\n \n vector<int> left, right;\n \n int root = nums[0];\n for(int i = 1; i < m; i++) {\n \n if(nums[i] < root) {\n left.push_back(nums[i]);\n } else {\n right.push_back(nums[i]);\n }\n \n }\n \n ll leftways = solve(left) % MOD;\n ll rightways = solve(right) % MOD;\n \n return (((leftways * rightways)%MOD) * PT[m-1][left.size()]) % MOD;\n \n }\n \n int numOfWays(vector<int>& nums) {\n int n = nums.size();\n \n \n PT.resize(n+1);\n \n for(int i = 0; i <= n; i++) {\n \n PT[i] = vector<long long>(i+1, 1);\n \n for(int j = 1; j < i; j++) {\n PT[i][j] = (PT[i-1][j-1] + PT[i-1][j]) % MOD;\n }\n }\n \n \n return (solve(nums)-1) % MOD;\n }\n};\n``` | 2 | 1 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Easy C++ solution (It's mainly about nCr) | easy-c-solution-its-mainly-about-ncr-by-9455f | I have calculated nCr using binary exponentiation and Class 12th nCr formula and Modular multiplicative inverse.\n\n```\nnCr= n! / r!(n-r)!\n\nclass Solution {\ | absolute-mess | NORMAL | 2023-06-16T10:08:10.318516+00:00 | 2023-06-16T10:08:10.318535+00:00 | 314 | false | I have calculated nCr using binary exponentiation and Class 12th nCr formula and Modular multiplicative inverse.\n\n```\nnCr= n! / r!*(n-r)!\n\nclass Solution {\npublic:\n long long fac[1001];\n int mod=1e9+7;\n void fact() { // To calculate the Factorial and mod for value in range\n fac[0]=1;\n for(int i=1;i<=1000;i++) {\n fac[i]=1LL*fac[i-1]*i;\n fac[i]%=mod;\n }\n }\n long long bin(long long n, long long m) { //Binary Exponentiaition (log n calculation)\n long long ans=1;\n while(m) {\n if(m&1) {\n ans*=n; ans%=mod;\n }\n n*=n; n%=mod;\n m/=2;\n }\n return ans;\n }\n long long ncr(int n, int k) { // Calculating nCr using the above formula\n long long ans=fac[n];\n long long den=1LL*fac[k]*fac[n-k]%mod;\n return 1LL*(ans%mod*bin(den, mod-2)%mod)%mod; \n }\n long long dfs(vector<int>&nums) {\n int n=nums.size();\n if(n<3) return 1;\n vector<int> left, right;\n for(int i=1;i<n;i++) if(nums[i]<nums[0]) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n long long l1=dfs(left);\n long long r1=dfs(right);\n return 1LL*ncr(n-1, left.size())%mod*l1%mod*r1%mod;\n }\n int numOfWays(vector<int>& nums) {\n fact();\n return (int) dfs(nums)-1;\n }\n}; | 2 | 1 | ['Divide and Conquer', 'C'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Simple Recursive Approach C++ code | simple-recursive-approach-c-code-by-meow-36pd | Intuition\nDivide and Conquer technique via recursion \n\n# Approach\nstoring left subtree in left array and right subtree in right array\ntotal number of ways | meowzies | NORMAL | 2023-06-16T09:40:52.885052+00:00 | 2023-06-16T09:41:18.139543+00:00 | 115 | false | # Intuition\nDivide and Conquer technique via recursion \n\n# Approach\nstoring left subtree in left array and right subtree in right array\ntotal number of ways can be achieved by no of arranging left subtree * no of ways of arranging right subtree * nCr\n\n\n# Code\n```\nclass Solution {\n int mod=1e9+7;\npublic:\n long long power(long long x,int y, int p)\n {\n long long res = 1; \n x = x % p; \n while (y > 0)\n {\n if (y & 1)\n res = (res * x) % p;\n y = y >> 1; \n x = (x * x) % p;\n }\n return res;\n}\n\nlong long modInverse(unsigned long long n,int p)\n{\n return power(n, p - 2, p);\n}\n\nlong long nCrModPFermat(long long n, int r, int p)\n{\n if (n < r)\n return 0;\n if (r == 0)\n return 1;\n \n long long fac[n + 1];\n fac[0] = 1;\n for (int i = 1; i <= n; i++)\n fac[i] = (fac[i - 1] * i) % p;\n \n return (fac[n] * modInverse(fac[r], p) % p\n * modInverse(fac[n - r], p) % p)\n % p;\n}\n long long lrbst(vector<int>& nums){\n int n=nums.size();\n if(n<=2) return 1;\n int root=nums[0];\n vector<int> left;\n vector<int> right;\n for(int i=1; i<n; i++){\n if(nums[i]<root) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n }\n int l=left.size();\n int r=right.size();\n\n long long lb=lrbst(left);\n long long rb=lrbst(right);\n return ((lb%mod*rb%mod)%mod*nCrModPFermat(n-1,l,mod))%mod;\n }\n\npublic:\n int numOfWays(vector<int>& nums) {\n long long ans=lrbst(nums);\n return ans-1;\n }\n};\n``` | 2 | 0 | ['Math', 'Divide and Conquer', 'Binary Search Tree', 'Recursion', 'C++'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | Java Solution | Permutations & Combinations | java-solution-permutations-combinations-8zcin | Code\n\nclass Solution {\n public int numOfWays(int[] nums) {\n List<Integer> arr=new ArrayList<>();\n for(int i=0; i<nums.length; i++) {\n | adarsh-mishra27 | NORMAL | 2023-06-16T07:38:14.401221+00:00 | 2023-06-16T07:40:20.920879+00:00 | 1,344 | false | # Code\n```\nclass Solution {\n public int numOfWays(int[] nums) {\n List<Integer> arr=new ArrayList<>();\n for(int i=0; i<nums.length; i++) {\n arr.add(nums[i]);\n }\n\n int n=nums.length;\n pascal=new long[n+1][n+1];\n pascal[0][0]=1;\n //nCr = n-1Cr-1 + n-1Cr\n for(int i=1; i<=n; i++) {\n pascal[i][0]=1;\n for(int j=1; j<i; j++) {\n pascal[i][j] = (pascal[i-1][j-1]+pascal[i-1][j])%MOD;\n }\n pascal[i][i]=1;\n }\n /*\n //print pascal\'s triangle for debugging\n // for(int i=0;i<pascal.length;i++) \n // System.out.println(Arrays.toString(pascal[i]));\n */\n\n return (int)(util(arr)-1);\n }\n\n private final long MOD=(long)1e9+7;\n\n //calculating nCR using pascal\'s triangle because factorial will cause long overflow\n private long pascal[][];\n private long nCr(int n, int r) { \n return pascal[n][r];\n }\n \n private long util(List<Integer> arr) {\n if(arr.size()<=2) return 1;\n\n List<Integer> left=new ArrayList<>();\n List<Integer> right=new ArrayList<>();\n int root=arr.get(0);\n for(int child: arr) {\n if(child==root) continue;\n if(child<root) {\n left.add(child);\n }else {\n right.add(child);\n }\n }\n\n int x=left.size();\n int y=right.size();\n long combi=nCr(x+y, x)%MOD;\n long get=(util(left)*util(right))%MOD;\n long ret=(combi*get)%MOD;\n return ret;\n }\n}\n``` | 2 | 0 | ['Divide and Conquer', 'Binary Search Tree', 'Combinatorics', 'Binary Tree', 'Java'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | [ C++ ] [ Dynamic Programming + DFS ] | c-dynamic-programming-dfs-by-sosuke23-d850 | Code\n\nclass Solution {\n int mod = 1e9 + 7;\n int combination(int k, int n, int mod) {\n if (k > n - k) k = n - k;\n vector<int> dp(k + 1) | Sosuke23 | NORMAL | 2023-06-16T01:04:46.647630+00:00 | 2023-06-16T01:04:46.647649+00:00 | 1,504 | false | # Code\n```\nclass Solution {\n int mod = 1e9 + 7;\n int combination(int k, int n, int mod) {\n if (k > n - k) k = n - k;\n vector<int> dp(k + 1);\n dp[0] = 1;\n for (int i = 1; i <= n; ++i) {\n for (int j = min(i, k); j > 0; --j) dp[j] = (dp[j] + dp[j - 1]) % mod;\n }\n return dp[k];\n }\n int dfs(vector<int> &A) {\n if (A.size() <= 1) return 1;\n int root = A[0];\n vector<int> left, right;\n for (int i = 1; i < A.size(); ++i) {\n if (A[i] < root) left.push_back(A[i]);\n else right.push_back(A[i]);\n }\n return ((long)combination(left.size(), A.size() - 1, mod) * dfs(left)) % mod * dfs(right) % mod;\n }\npublic:\n int numOfWays(vector<int>& A) {\n return (dfs(A) - 1 + mod) % mod;\n }\n};\n``` | 2 | 0 | ['C++'] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | Fastest Solution Yet | fastest-solution-yet-by-x7d309777-e0v2 | Intuition\nGiven an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elem | AZ777 | NORMAL | 2023-06-16T00:06:33.112306+00:00 | 2023-06-19T18:28:43.069497+00:00 | 422 | false | # Intuition\nGiven an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.\n\nThe code works as follows:\n1. It first defines a function ```cnr()``` that calculates the combination of two numbers. This function is used later in the code to calculate the number of ways to split a range of numbers into two smaller ranges.\n\n2. It then defines two arrays, ```leng``` and ```cnt```, which store the length and count of each range of numbers, respectively.\n\n3. It then iterates through the array ```nums``` in reverse order. For each number ```p```, it calculates the length of the range of numbers to the left of ```p``` (stored in ```h```) and the length of the range of numbers to the right of ```p``` (stored in ```k```).\n\n4. It then calculates the number of ways to split the range of numbers from ```p-h``` to ```p+k``` into two smaller ranges (left sub-tree and right sub-tree). This is done by multiplying the count of the range of numbers to the left of ```p``` (stored in ```cnt[p-1]```), the count of the range of numbers to the right of ```p``` (stored in ```cnt[p+1]```), and the combination of ```h+k``` and ```h```.\n\n5. It then updates the length and count of the range of numbers from ```p-h``` to ```p+k``` to be ```h+k+1``` and ```t```, respectively.\n\n6. It repeats steps 3-5 for each number in ```nums```.\n\n7. It then returns the count of the range of numbers from ```1 to n```, which is stored in ```cnt[1]```.\n\n\n\n\n# Approach\nUse bottom-up recursion with merge interval.\n\n# Complexity\n- Time complexity:$$O(n^2)$$. This is because the code iterates through the array nums once, and for each number in the array, it calculates the length and count of the range of numbers to the left and right of the number. The space complexity of the code is O(n), because it stores the arrays leng and cnt.\n\n- Space complexity:$$O(n^2)$$. This is because the two arrays leng and cnt both have a size of n+2, and each element in the arrays takes up constant space. Therefore, the total space complexity is O(n^2).\n\nHere is a breakdown of the space complexity of each of the two arrays:\n\n - leng: This array stores the lengths of the intervals that have been processed so far. The size of this array is n+2 because we need to store the lengths of all intervals, including the empty interval at the beginning and end.\n \n - cnt: This array stores the number of ways to partition the intervals that have been processed so far. The size of this array is also n+2 because we need to store the number of ways to partition all intervals, including the empty partition at the beginning and end.\n\n\nThe total space complexity is then the sum of the space complexities of the two arrays, which is O(n^2).\n\n\n\n# Code\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n mod = 1000000007\n n = len(nums)\n\n\n # stores the length of each range of numbers, respectively.\n leng = [0]*(n+2) \n\n # stores the count of each range of numbers, respectively.\n cnt = [1]*(n+2) \n\n # Iterate the array in reverse order\n for p in nums[::-1]: \n # k consecutive values larger than p (on the left) are already in BST if leng[p+1] > 0 indicates that. Length [p+1] and h are the respective integers in the right child BST of p.\n h,k = leng[p-1],leng[p+1] \n\n # The size of the BST rooted at p should be used to update the lengths at the rightmost and leftmost numbers in the BST (consecutive intervals). Because it won\'t be needed in the subsequent computation of length and cnt, the numbers in between (p-h, p+k) don\'t need to be updated.\n leng[p-h]=leng[p+k]=h+k+1 \n\n # The number of permutated arrays that can construct the BST of the left child and the right child of p is given by dp(BST rooted at p) = dp(left(p-1))*dp(right(p+1))*C(left+right,right).\n t = (cnt[p-1]*cnt[p+1]%mod)*comb(h+k,h)%mod \n\n # Only the cnt\'s rightmost and leftmost elements should be updated because those two numbers will be the only ones used in the next merge interval.\n cnt[p-h]=cnt[p+k]=t \n\n # return the number of ways to reorder nums\n return (cnt[1]-1)%mod \n``` | 2 | 0 | ['Backtracking', 'Binary Search Tree', 'Recursion', 'Combinatorics', 'Python3'] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | [C++], O(n^2) But easy to understand | c-on2-but-easy-to-understand-by-amasub22-p333 | Intuition\nThe problem asks us to find the number of ways to reorder an input array nums such that a binary search tree (BST) constructed from the reordered arr | amasub222 | NORMAL | 2023-04-28T08:56:45.200650+00:00 | 2023-04-28T08:56:45.200682+00:00 | 462 | false | # Intuition\nThe problem asks us to find the number of ways to reorder an input array nums such that a binary search tree (BST) constructed from the reordered array is identical to the BST formed from the original array. This problem can be solved by first understanding the properties of a BST, and then using dynamic programming to recursively count the number of ways to construct the BST.\n\n# Approach\nWe can start by observing that the root of the BST should always be the first element, let\'s call it `ref_val`. We can then partition the remaining elements of nums into two subarrays - one containing the elements smaller than the root, let\'s call it `x`, and the other containing the elements greater than the root, let\'s call it `y`. \n\nNow, for the BST construction to be valid, we can merge `x` and `y` in any order as long as we maintain the relative order within `x` and `y`. In other words, if we keep the relative order in `x` and `y`, however we choose to merge `x` and `y`, it is a valid answer. The number of ways to merge `x` and `y` can be calculated using the binomial coefficient (n choose k), where n is the total number of elements in x and y, and k is the number of elements in any of subarrays (since $$ncr(x+y,x) = ncr(x+y,y)$$). \nThis yields to: \n$$result = ncr(x.size()+y.size(), x.size())$$\nas the `result` would be a very large number, we utilize `nCrModp` to calculate a moded `ncr`. \n\n*BUT*, there is an issue in the solution, what if `x` or `y` could be reordered and again BST construction would be the same? We should multiply previously calculated `result` by number of possible reorders of `x` and `y` and this is done by recursively calling `numOfWays` on `x` and `y` to calculate `multiply_factor`\n\nNotice that we counted ALL possible ways including the one in the input, so we should subtract final result by one to get correct answer.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\nThe time complexity of the solution is $$O(n^2)$$, where `n` is the length of the input array `nums`. This is because the `numOfWays` function recursively calls itself on the subarrays of `nums`, and the size of the subarrays being processed in each recursive call can be as large as `n`. In addition, the `nCrModp` function used to calculate the binomial coefficient has a time complexity of $$O(r)$$, where r is the size of the smaller subarray, which can also be as large as `n`.\n\n- Space complexity: $$O(n^2)$$\n\nThe space complexity of the solution is also $$O(n^2)$$, as the `nCrModp` function uses an array of size `r+1`, where `r` is the size of the smaller subarray, which can again be as large as `n`. In addition, the recursive calls to `numOfWays` create additional space for the call stack.\n# Code\n```\n#define ll long long\n#define MOD ((ll) (1e9+7))\n\nclass Solution {\npublic:\n // https://www.geeksforgeeks.org/introduction-and-dynamic-programming-solution-to-compute-ncrp/\n // Returns nCr % p\n ll nCrModp(ll n, ll r, ll p)\n {\n // Optimization for the cases when r is large\n if (r > n - r)\n r = n - r;\n \n // The array C is going to store last row of\n // pascal triangle at the end. And last entry\n // of last row is nCr\n ll C[r + 1];\n memset(C, 0, sizeof(C));\n \n C[0] = 1; // Top row of Pascal Triangle\n \n // One by constructs remaining rows of Pascal\n // Triangle from top to bottom\n for (ll i = 1; i <= n; i++) {\n \n // Fill entries of current row using previous\n // row values\n for (ll j = min(i, r); j > 0; j--)\n \n // nCj = (n-1)Cj + (n-1)C(j-1);\n C[j] = (C[j] + C[j - 1]) % p;\n }\n return C[r];\n }\n \n int numOfWays(vector<int>& nums) {\n if(nums.size() < 1 ) return 0;\n\n int ref_val=nums[0];\n vector<int> greater_than, smaller_than;\n\n //dividing to smaller and bigger vector\n for(auto &a:nums){\n if(a<ref_val) smaller_than.push_back(a); \n else if(a>ref_val) greater_than.push_back(a); \n }\n\n //FOR THE SAKE OF SIMPLICTY, EXTRA VARIABLES ARE CREATED\n\n //counting how many ways we can reorder `smaller_than` and `greater_than` themselves \n ll multiply_factor=1ll*(numOfWays(smaller_than)+1)*(numOfWays(greater_than)+1);\n \n //keeping moded value of `multiply_factor` as result\n ll result = multiply_factor % MOD;\n\n //counting how many ways we can merge `smaller_than` and `greater_than`, and multipling it by result \n result*= nCrModp(smaller_than.size()+ greater_than.size(), smaller_than.size(), MOD);\n\n //subtracting input from all possible values and return final result\n return (result-1)%MOD;\n \n }\n};\n``` | 2 | 0 | ['Divide and Conquer', 'Dynamic Programming', 'Combinatorics', 'C++'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ simple and short DFS solution | c-simple-and-short-dfs-solution-by-cal_a-otca | \n# Code\n\nclass Solution {\n const int mod = 1e9 + 7;\n long inverse(long num) {\n if (num == 1) {\n return 1;\n }\n ret | cal_apple | NORMAL | 2023-01-22T08:49:57.593723+00:00 | 2023-01-22T08:49:57.593765+00:00 | 462 | false | \n# Code\n```\nclass Solution {\n const int mod = 1e9 + 7;\n long inverse(long num) {\n if (num == 1) {\n return 1;\n }\n return mod - mod / num * inverse(mod % num) % mod;\n }\n\n int dfs(vector<int>& nums) {\n int N = nums.size();\n if (N <= 2) {\n return 1;\n }\n vector<int> left, right;\n for (int i = 1; i < N; i++) {\n if (nums[i] < nums[0]) {\n left.push_back(nums[i]);\n } else {\n right.push_back(nums[i]);\n }\n }\n\n int a = left.size();\n int b = right.size();\n long res = 1;\n\n // relative order between left and right\n // (a+b)! / (b! * a!)\n for (int i = b+1; i <= a + b; i++) {\n res = res * i % mod;\n }\n for (int i = 1; i <= a; i++) {\n // res * inverse(i) == res / i\n res = res * inverse(i) % mod;\n }\n\n // order within left: dfs(left)\n // order within right: dfs(right)\n return res * dfs(left) % mod * dfs(right) % mod;\n }\npublic:\n int numOfWays(vector<int>& nums) {\n return dfs(nums) - 1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | β Python3 Solution | Combination | python3-solution-combination-by-satyam20-j9ku | Code\n\nclass Solution:\n def numOfWays(self, A):\n n = len(A)\n mod = 10 ** 9 + 7\n def dfs(i, l, h):\n if h == l + 1: retur | satyam2001 | NORMAL | 2022-12-22T07:25:13.477916+00:00 | 2022-12-22T07:25:13.477957+00:00 | 710 | false | # Code\n```\nclass Solution:\n def numOfWays(self, A):\n n = len(A)\n mod = 10 ** 9 + 7\n def dfs(i, l, h):\n if h == l + 1: return 1\n if l < A[i] < h:\n return (dfs(i + 1, l, A[i]) * dfs(i + 1, A[i], h) * math.comb(h - l - 2, A[i] - l - 1)) % mod\n return dfs(i + 1, l, h)\n return dfs(0, 0, n + 1) - 1\n``` | 2 | 0 | ['Recursion', 'Combinatorics', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Java | Recursive Solution - 88% fast | java-recursive-solution-88-fast-by-basel-aozy | \npublic class Solution {\n private Map<TreeNode, Integer> map;\n private int mod = 1000000007;\n \n public Solution() {\n map = new HashMap< | BaselAhmed | NORMAL | 2022-08-26T18:27:13.082306+00:00 | 2022-08-26T18:27:13.082358+00:00 | 1,350 | false | ``` \npublic class Solution {\n private Map<TreeNode, Integer> map;\n private int mod = 1000000007;\n \n public Solution() {\n map = new HashMap<>();\n }\n class TreeNode {\n public int val;\n public TreeNode left;\n public TreeNode right;\n\n public TreeNode(int val) {\n this.val = val;\n left = null;\n right = null;\n }\n }\n\n public int numOfWays(int[] nums) {\n TreeNode root = buildTree(nums);\n return (int) (numOfWays(root) % mod) - 1;\n }\n \n private long numOfWays(TreeNode node) {\n if (node == null)\n return 1;\n int n = numOfNodes(node.left);\n int m = numOfNodes(node.right);\n \n return ((((binomialCoeff(n + m, n) % mod) * numOfWays(node.left)) % mod) * numOfWays(node.right)) % mod;\n }\n\n\t// calulate the number of descendants of this node including the node itself\n private int numOfNodes(TreeNode node) {\n\t\t// dp to decrease the runtime\n if (map.containsKey(node))\n return map.get(node);\n if (node == null) \n return 0;\n \n int num = 1 + numOfNodes(node.left) + numOfNodes(node.right);\n map.put(node, num);\n return num;\n }\n \n\t// method to calculate the value of nCk\n private int binomialCoeff(int n, int k) {\n int[] c = new int[k + 1];\n c[0] = 1;\n \n for (int i = 1; i <= n; i++) {\n for (int j = Math.min(i, k); j > 0; j--) \n c[j] = (c[j] + c[j - 1]) % mod;\n }\n return c[k] % mod;\n }\n\n \n private TreeNode buildTree(int[] nums) {\n TreeNode tree = null;\n for (int num : nums)\n tree = insert(tree, num);\n return tree;\n }\n\n private TreeNode insert(TreeNode root, int val) {\n if (root == null)\n return new TreeNode(val);\n\n if (val < root.val)\n root.left = insert(root.left, val);\n else if (val > root.val)\n root.right = insert(root.right, val);\n\n return root;\n }\n\n}\n\n``` | 2 | 0 | ['Dynamic Programming', 'Binary Search Tree', 'Combinatorics', 'Java'] | 1 |
number-of-ways-to-reorder-array-to-get-same-bst | JavaScript Solution | Recursion + Combination | javascript-solution-recursion-combinatio-uy2h | \nvar numOfWays = function(nums) {\n const x = numOfWaysHelper(nums) - 1n;\n return x % 1_000_000_007n;\n}\nvar numOfWaysHelper = function(nums) {\n if | mr-harry | NORMAL | 2021-12-28T13:47:36.405363+00:00 | 2021-12-28T13:47:36.405405+00:00 | 694 | false | ```\nvar numOfWays = function(nums) {\n const x = numOfWaysHelper(nums) - 1n;\n return x % 1_000_000_007n;\n}\nvar numOfWaysHelper = function(nums) {\n if(nums.length < 3)\n return 1n;\n \n const root = nums[0];\n const left = nums.filter(p => p < root);\n const right = nums.filter(p => p > root);\n return BigInt(comb(left.length + right.length, left.length) * numOfWaysHelper(left) * numOfWaysHelper(right));\n};\n\nfunction comb(n, k){\n n = BigInt(n);\n k = BigInt(k);\n if(n < 2)\n return 1n;\n return fact(n)/fact(n-k)/fact(k);\n}\n\nconst factCache = new Map();\n\nfunction fact(n){\n if(n<2)\n return 1n;\n if(factCache.has(n))\n return factCache.get(n);\n \n var result = BigInt(n) * fact(n - 1n);\n factCache.set(n, result);\n return result;\n}\n``` | 2 | 0 | ['JavaScript'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Python3 solution | python3-solution-by-_yash-0z8e | \nclass node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution:\n def BST(self, r | _yash_ | NORMAL | 2021-06-08T10:45:15.780881+00:00 | 2021-06-08T10:45:15.780916+00:00 | 1,601 | false | ```\nclass node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution:\n def BST(self, root, cur):\n if cur.val < root.val:\n if root.left == None:\n root.left = cur\n return\n else:\n self.BST(root.left, cur)\n elif cur.val > root.val:\n if root.right == None:\n root.right = cur\n return\n else:\n self.BST(root.right, cur)\n \n def solve(self, root):\n if root.left == None and root.right == None:\n return 1\n left = 0 ; right = 0\n if root.left is not None:\n left = self.solve(root.left)\n if root.right is not None:\n right = self.solve(root.right)\n self.total *= math.comb(left + right, left)\n return left + right + 1\n \n def numOfWays(self, nums: List[int]) -> int:\n import math\n self.total = 1\n root = node(nums[0])\n for i in range(1, len(nums)):\n self.BST(root, node(nums[i]))\n self.solve(root)\n return (self.total - 1) % (int(1e9) + 7)\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | [C++] algebra, module-inverse, comb(N, K) | c-algebra-module-inverse-combn-k-by-mult-0uw0 | \nclass Solution {\n const int64_t MOD = 1000000007;\n \n int64_t comb(int N, int K) {\n int64_t nx = 1;\n // i!\n for (int64_t i | multivacx | NORMAL | 2021-05-23T03:56:57.292242+00:00 | 2021-05-23T03:56:57.292270+00:00 | 550 | false | ```\nclass Solution {\n const int64_t MOD = 1000000007;\n \n int64_t comb(int N, int K) {\n int64_t nx = 1;\n // i!\n for (int64_t i = 2; i <= N; ++i) nx = nx * i % MOD;\n\n const int M = max(K, N - K) + 1;\n vector<int64_t> inv(M, 0), inv_kx(M, 0);\n inv[0] = inv_kx[0] = inv[1] = inv_kx[1] = 1;\n // https://cp-algorithms.com/algebra/module-inverse.html\n // 1 / i!\n for (int64_t i = 2; i < M; ++i) {\n inv[i] = MOD - (MOD / i) * inv[MOD % i] % MOD;\n inv_kx[i] = inv_kx[i - 1] * inv[i] % MOD;\n // cout << i << ":" << inv_kx[i] << " ";\n }\n \n // N! / (K! * (N - K)!)\n return nx * inv_kx[K] % MOD * inv_kx[N - K] % MOD;\n }\n \n int64_t ways(vector<int>& nums) {\n if (nums.size() <= 2) return 1;\n \n vector<int> l, r;\n for (int i = 1; i < nums.size(); ++i)\n nums[i] < nums[0] ? l.push_back(nums[i]) : r.push_back(nums[i]);\n int64_t c = comb(l.size() + r.size(), l.size()), lw = ways(l), rw = ways(r);\n return c * lw % MOD * rw % MOD;\n }\n \npublic:\n int numOfWays(vector<int>& nums) {\n // root = nums[0]\n // l[i] < root; r[i] > root\n // comb(l.size + r.size, l.size) * numOfWays(l) * numOfWays(r) - 1\n \n return ways(nums) - 1; \n }\n};\n``` | 2 | 0 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Easy and commented [C++] solution | easy-and-commented-c-solution-by-leetcod-4qps | \n#define ll long long\n\nclass Solution {\npublic:\n \n ll MOD=1e9L+7;\n ll dp[1001][1001]; // dp[i][j] = iCj (i choose j)\n \n ll util(vector<i | leetcode07 | NORMAL | 2020-11-14T18:33:21.116257+00:00 | 2020-11-14T18:33:21.116298+00:00 | 709 | false | ```\n#define ll long long\n\nclass Solution {\npublic:\n \n ll MOD=1e9L+7;\n ll dp[1001][1001]; // dp[i][j] = iCj (i choose j)\n \n ll util(vector<int>& v){\n int n=v.size();\n if(n==0) return 1; // base case when binary search tree is empty\n \n int root=v[0]; // root of the binary search tree\n \n vector<int> left, right;\n \n for(int i=1; i<n; i++){\n if(v[i]>root){\n right.push_back(v[i]); // right children of root\n }\n else if(v[i]<root){\n left.push_back(v[i]); // left children of root\n }\n }\n \n ll left_ans=util(left); // number of ways to form left subtree\n ll right_ans=util(right); // number of ways to form right subtree\n \n ll ans=(ll)left_ans*right_ans%MOD; // merging the answer of left and right (standard divide conquer strategy)\n \n ans=(ll)ans*dp[n-1][(int)left.size()]%MOD; // also among total n-1 insertions in this tree there are (n-1)C(left.size()) ways to interleave the left and right insertions\n \n return ans;\n }\n \n int numOfWays(vector<int>& nums) {\n dp[0][0]=1;\n \n for(ll i=1; i<=nums.size(); i++){\n dp[i][0]=1;\n dp[i][i]=1;\n for(ll j=1; j<i; j++){\n dp[i][j]=(dp[i-1][j-1]+dp[i-1][j])%MOD;\n }\n }\n \n ll ans=util(nums);\n \n ans=(ans+MOD-1)%MOD; // need to subtract the already given ordering\n \n return ans; // :)\n }\n};\n``` | 2 | 1 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Java | Bottom-Up DP + Recursion | O(n^2) Time Complexity | java-bottom-up-dp-recursion-on2-time-com-d8pc | \n/*\n\nSuppose we have \'m\' elements in one array and \'n\' elements in another and we need to arrange \'n\' elemnts around \'m\' elements of first array with | ashish10comp | NORMAL | 2020-11-11T05:38:09.141731+00:00 | 2020-11-11T05:42:02.636708+00:00 | 680 | false | ```\n/*\n\nSuppose we have \'m\' elements in one array and \'n\' elements in another and we need to arrange \'n\' elemnts around \'m\' elements of first array without breaking the order of elements in any of the arrays.\n\narray first = _ l1 _ l2 _ l3 _ ..... _ li-2 _ li-1 _ li _ li+1 _ ..... _ lm-2 _ lm-1 _ lm _\n\narray second = r1 r2 r3 ..... rj-2 rj-1 rj rj+1 ..... rn-1 rn\n\nLet DP[i][j] = # of ways to arrange \'j\'th elements of second array around \'i\' elements of first array without breaking the order of elements in any of the arrays.\n\nFor placing the \'j\'th element (rj) of second array we have DP[i][j - 1] ways as \'j\'th element will follow order and will be placed only after \'j-1\'th element.\nAnd this \'j\' element could have occurred after \'i\'th element (li) of first array or after \'i-1\'th element (li-1) of first array or after \'i-2\'th element (li-2) of first array and so on.\n\nHence, we have\nDP[i][j] = DP[i][j - 1] + DP[i - 1][j - 1] + DP[i - 2][j - 1] + ..... + DP[0][j - 1] ; i E [1, m], j E [1, n], k E [0, i]\n\nIn General :\nDP[i][j] = sum(DP[i - k][j - 1]) ; i E [1, m], j E [1, n], k E [0, i]\nDP[i][j] = 1 ; i == 0, j E [1, n]\nDP[i][j] = 1 ; i [1, m], j == 0\n\nresult = use DP to get solution by calling recursively for each subtree and multiply each combination.\nThen \'1\' is subtrated as we already have one combination given as input.\n\n-----------------------------------------------------------------------------------------------------------------\n\nMore formally :\nDP[i][j] = DP[i][j - 1] + DP[i - 1][j - 1] + DP[i - 2][j - 1] + ..... + DP[1][j - 1] + DP[0][j - 1] ; ..... (equation 1)\n\nPut \'i-1\' in place of \'i\' to get DP[i - 1][j]\nDP[i - 1][j] = DP[i - 1][j - 1] + DP[i - 2][j - 1] + DP[i - 3][j - 1] + ..... + DP[1][j - 1] + DP[0][j - 1] ; ..... (equation 2)\n\nSubtracting both above equations, we get\n(equation 1) - (equation 2)\n=> DP[i][j] - DP[i - 1][j] = DP[i][j - 1] ;\n=> DP[i][j] = DP[i][j - 1] + DP[i - 1][j] ;\n\n-----------------------------------------------------------------------------------------------------------------\n\nFinal equations :\nDP[i][j] = DP[i][j - 1] + DP[i - 1][j] ; i E [1, m], j E [1, n] ----- here m and n both are equal to length of the input array\nDP[i][j] = 1 ; i == 0, j E [1, n]\nDP[i][j] = 1 ; i [1, m], j == 0\n\nresult = use DP to get solution by calling recursively for each subtree and multiply each combination. Then \'1\' is subtrated as we already have one combination given as input.\n\n*/\n\nclass Solution {\n public int numOfWays(int[] nums) {\n int length = nums.length, MOD = 1000000007;\n long[][] DP = new long[length + 1][length + 1];\n for(int j = 0; j <= length; j++) {\n DP[0][j] = 1;\n }\n for(int i = 0; i <= length; i++) {\n DP[i][0] = 1;\n }\n for(int i = 1; i <= length; i++) {\n for(int j = 1; j <= length; j++) {\n DP[i][j] = ((DP[i][j - 1] + DP[i - 1][j]) % MOD);\n }\n }\n return ((int) getNumberOfWays(nums, DP) - 1);\n }\n\n private long getNumberOfWays(int[] nums, long[][] DP) {\n int length = nums.length, m = 0, n = 0, MOD = 1000000007;\n if(length == 0) {\n return 1;\n }\n for(int i = 2; i <= length; i++) {\n if(nums[i - 1] < nums[0]) {\n m++;\n } else {\n n++;\n }\n }\n int[] leftNodes = new int[m];\n int[] rightNodes = new int[n];\n m = 0;\n n = 0;\n for(int i = 2; i <= length; i++) {\n if(nums[i - 1] < nums[0]) {\n leftNodes[m++] = nums[i - 1];\n } else {\n rightNodes[n++] = nums[i - 1];\n }\n }\n return (((DP[m][n] * getNumberOfWays(leftNodes, DP) % MOD) * getNumberOfWays(rightNodes, DP)) % MOD);\n }\n}\n``` | 2 | 0 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Simple C++ Solution | simple-c-solution-by-mayankdhiman-d8pl | \nclass Solution {\npublic:\n vector < vector < long long > > pascal;\n int MOD = 1e9 + 7;\n \n int numOfWays(vector<int>& nums) {\n int N = | mayankdhiman | NORMAL | 2020-08-30T18:51:57.290222+00:00 | 2020-08-30T18:51:57.290277+00:00 | 248 | false | ```\nclass Solution {\npublic:\n vector < vector < long long > > pascal;\n int MOD = 1e9 + 7;\n \n int numOfWays(vector<int>& nums) {\n int N = nums.size();\n pascal = vector < vector < long long > > (N + 1);\n for (int i = 0; i < N + 1; i ++){\n pascal[i] = vector < long long > (i + 1, 1);\n for (int j = 1; j < i; j ++){\n pascal[i][j] = (pascal[i - 1][j] + pascal[i - 1][j - 1])%MOD;\n }\n }\n return dfs(nums) - 1;\n }\n \n int dfs(vector < int > nums){\n if (nums.size() <= 2)\n return 1;\n vector < int > left, right;\n for (int i = 1; i < int(nums.size()); i ++){\n if (nums[i] < nums[0])\n left.push_back(nums[i]);\n else\n right.push_back(nums[i]);\n }\n return (((dfs(left) * pascal[nums.size() - 1][left.size()]) % MOD) * dfs(right))%MOD;\n }\n};\n``` | 2 | 0 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | [Python] Simple code beats 100% in runtime with explanations | python-simple-code-beats-100-in-runtime-d4nz0 | Note: \nThe difficult part is to calculate 1000!\nThis solution is not the best one, but is very easy to come up with.\nIt is not good because number gets very | lichuan199010 | NORMAL | 2020-08-30T06:56:20.546482+00:00 | 2020-08-30T07:15:01.785244+00:00 | 232 | false | Note: \nThe difficult part is to calculate 1000!\nThis solution is not the best one, but is very easy to come up with.\nIt is not good because number gets very large as the number of nodes gets bigger.\nIdeally, we should use modular calculations.\n\nUsing pascal\'s triangle\uFF08\u6768\u8F89\u4E09\u89D2\uFF09to calculate all combinations is a better solution.\nBut my version is very simple, so I shared it.\nIf people are interested, go check other solutions for building a tree / using pascal\'s triangle as well.\n\n\t### Precalculation of 0! to 1000! so that we don\'t need to calculate them each time\n\tfacall = [1]\n\tp = 10**9 + 7\n\tresult = 1\n\tfor i in range(1, 1001):\n\t\tresult = (result * i)\n\t\tfacall.append(result)\n\n\tclass Solution:\n\t\tdef numOfWays(self, nums: List[int]) -> int:\n\t\t\tmod = 10**9 + 7\n\n\t\t\tdef helper(nums):\n\t\t\t\t# base case of no node or 1 node\n\t\t\t\tif len(nums) <= 1: return 1\n\n\t\t\t\troot = nums[0]\n\t\t\t\t# find how many numbers are in the left and right subtree\n\t\t\t\tnumsleft = []\n\t\t\t\tnumsright = []\n\t\t\t\tfor n in nums[1:]:\n\t\t\t\t\tif n < root:\n\t\t\t\t\t\tnumsleft.append(n)\n\t\t\t\t\telse:\n\t\t\t\t\t\tnumsright.append(n)\n\n\t\t\t\tleft = helper(numsleft)\n\t\t\t\tright = helper(numsright)\n\t\t\t\t\n\t\t\t\t# for each order of numsleft and numsright\n\t\t\t\t# each time, we can randomly choose one node from numsleft or nums right\n\t\t\t\t# so it is choose len(numsleft) from (len(numsleft) + len(numsright))\n\t\t\t\t# there are left * right combinations\n\t\t\t\treturn (left * right * facall[len(nums)-1] // facall[len(numsleft)] // facall[len(numsright)])%mod\n\t\t\t\n\t\t\t# subtract 1 here because the current order should not be counted.\n\t\t\treturn (helper(nums)-1)%mod | 2 | 1 | [] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Python short and simple | python-short-and-simple-by-ritam777-wbsm | Simple recursion\nNumber of ways of re-arranging current array = (number of ways of rearranging m values of left subtree) * (number of ways of rearranging n val | ritam777 | NORMAL | 2020-08-30T04:17:06.041394+00:00 | 2020-08-30T04:24:12.455384+00:00 | 318 | false | **Simple recursion**\nNumber of ways of re-arranging current array = (number of ways of rearranging **m** values of left subtree) * (number of ways of rearranging **n** values of right subtree) * (number of ways of inter-leaving two arrays of sizes m and n having unique integers such that order is preserved i.e. **xCy where x = m+n and y = n**).\n\nAt the end, we subtract 1 from the number of all combinations to account for input sequence which itself gives the same tree and should not be counted.\n\nRefer to "Number of ways to interleave two ordered sequences": https://math.stackexchange.com/a/666295\n\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n def countWays(nums):\n if not nums:\n return 1\n nums1 = [num for num in nums if num < nums[0]]\n nums2 = [num for num in nums if num > nums[0]]\n return countWays(nums1) * countWays(nums2) * math.comb(len(nums1) + len(nums2), len(nums2))\n \n return (countWays(nums)-1) % (10**9+7)\n``` | 2 | 1 | [] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | C++ Explanation | c-explanation-by-justinwongjianhui-1qed | Took me quite a while to get it, but the \nnumber of ways to arrange nums = ways to arrange the numbers in the left subtree * ways to arrange numbers in right s | justinwongjianhui | NORMAL | 2020-08-30T04:16:24.487844+00:00 | 2020-08-30T04:18:23.016294+00:00 | 688 | false | Took me quite a while to get it, but the \nnumber of ways to arrange nums = ways to arrange the numbers in the left subtree * ways to arrange numbers in right subtree * positions to fit the left/right subtree back into the original array\n\n```\nclass Solution {\npublic:\n int mod=1e9+7;\n long long power(long long a, long long b) {\n long long res=1;\n while (b>0) {\n if (b&1) res*=a, res%=mod;\n b/=2;\n a*=a;\n a%=mod;\n }\n return res;\n }\n long long choose(long long a, long long b) {\n long long res=1;\n for (long long i=1; i<=b; i++) {\n res*=(a-i+1);\n res%=mod;\n res*=power(i, mod-2);\n res%=mod;\n }\n return res;\n }\n long long solve(vector<int> nums) {\n if (nums.size()<=2) return 1;\n vector<int> left, right;\n for (int i=1; i<nums.size(); i++) {\n if (nums[i]<nums[0]) left.push_back(nums[i]);\n else right.push_back(nums[i]);\n }\n return ((choose(nums.size()-1, right.size())*solve(right)%mod)*solve(left))%mod;\n }\n int numOfWays(vector<int> &nums) {\n return solve(nums)-1;\n }\n};\n``` | 2 | 0 | [] | 2 |
number-of-ways-to-reorder-array-to-get-same-bst | Beats 94.59%of users with JavaScript | beats-9459of-users-with-javascript-by-ss-kke8 | \n# Code\n\nvar numOfWays = function(nums) {\n const x = numOfWaysHelper(nums) - 1n;\n return x % 1_000_000_007n;\n}\nvar numOfWaysHelper = function(nums) | SSDeepakReddy | NORMAL | 2023-10-14T05:35:48.098980+00:00 | 2023-10-14T05:35:48.099004+00:00 | 26 | false | \n# Code\n```\nvar numOfWays = function(nums) {\n const x = numOfWaysHelper(nums) - 1n;\n return x % 1_000_000_007n;\n}\nvar numOfWaysHelper = function(nums) {\n if(nums.length < 3)\n return 1n;\n \n const root = nums[0];\n const left = nums.filter(p => p < root);\n const right = nums.filter(p => p > root);\n return BigInt(comb(left.length + right.length, left.length) * numOfWaysHelper(left) * numOfWaysHelper(right));\n};\n\nfunction comb(n, k){\n n = BigInt(n);\n k = BigInt(k);\n if(n < 2)\n return 1n;\n return fact(n)/fact(n-k)/fact(k);\n}\n\nconst factCache = new Map();\n\nfunction fact(n){\n if(n<2)\n return 1n;\n if(factCache.has(n))\n return factCache.get(n);\n \n var result = BigInt(n) * fact(n - 1n);\n factCache.set(n, result);\n return result;\n}\n``` | 1 | 0 | ['JavaScript'] | 0 |
number-of-ways-to-reorder-array-to-get-same-bst | Combinations + DFS | C++ | combinations-dfs-c-by-tusharbhart-a8pu | \nclass Solution {\n int mod = 1e9 + 7;\n long dfs(vector<int> &nums, vector<vector<int>> &ncr) {\n int n = nums.size();\n if(n <= 2) return | TusharBhart | NORMAL | 2023-06-30T19:58:28.797221+00:00 | 2023-06-30T19:58:28.797244+00:00 | 22 | false | ```\nclass Solution {\n int mod = 1e9 + 7;\n long dfs(vector<int> &nums, vector<vector<int>> &ncr) {\n int n = nums.size();\n if(n <= 2) return 1;\n\n vector<int> l, r;\n for(int i=1; i<n; i++) {\n if(nums[i] < nums[0]) l.push_back(nums[i]);\n else r.push_back(nums[i]);\n }\n\n long left = dfs(l, ncr) % mod;\n long right = dfs(r, ncr) % mod;\n\n return ((ncr[n - 1][l.size()] * left) % mod * right) % mod;\n }\npublic:\n int numOfWays(vector<int>& nums) {\n int n = nums.size();\n vector<vector<int>> ncr(n + 1, vector<int>(n + 1, 1));\n\n for(int i=1; i<=n; i++) {\n for(int j=1; j<i; j++) {\n ncr[i][j] = (ncr[i - 1][j - 1] + ncr[i - 1][j]) % mod;\n }\n }\n \n return (dfs(nums, ncr) - 1) % mod;\n }\n};\n\n\n``` | 1 | 0 | ['Recursion', 'Combinatorics', 'C++'] | 0 |
Subsets and Splits