Problem solution · C++

Number of Ways to Reorder Array to Get Same BST

Number of Ways to Reorder Array to Get Same BST: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
46 lines
Start with the idea.

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

Approach

Sliding window or two pointers

For Number of Ways to Reorder Array to Get Same BST, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 46 lines of C++ from the credited upstream file 1569.cpp.
  • The implementation visibly relies on sequence storage.
  • 4 loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

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

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeNumber of Ways to Reorder Array to Get Same BST · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int numOfWays(vector<int>& nums) {    comb = generate(nums.size() + 1);    return ways(nums) - 1;  }  private:  static constexpr int kMod = 1'000'000'007;  // comb[n][k] := C(n, k)  vector<vector<int>> comb;   int ways(const vector<int>& nums) {    if (nums.size() <= 2)      return 1;     vector<int> left;    vector<int> right;     for (int i = 1; i < nums.size(); ++i)      if (nums[i] < nums[0])        left.push_back(nums[i]);      else        right.push_back(nums[i]);     long ans = comb[nums.size() - 1][left.size()];    ans = (ans * ways(left)) % kMod;    ans = (ans * ways(right)) % kMod;    return ans;  }   // Same as 118. Pascal's Triangle  vector<vector<int>> generate(int numRows) {    vector<vector<int>> comb;     for (int i = 0; i < numRows; ++i)      comb.push_back(vector<int>(i + 1, 1));     for (int i = 2; i < numRows; ++i)      for (int j = 1; j < comb[i].size() - 1; ++j)        comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % kMod;     return comb;  }}; 

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

Buy me a coffee ↗