Given two unsorted arrays of size N each, we are to determine if the Binary Search Tree constructed from them will be equal or not.
So, the elements of the array are picked and inserted into a basic (no balancing, no red-black, nothing) binary search tree. Given directly two arrays, can we determine whether they give rise to the same Binary Search Tree.
There is an obvious O(N2) worst case time complexity solution: Construct two trees, and compare their equality.
Is there a O(N) or an O(N log N) solution to this?
The idea of the problem that I am trying to extract is: The construction of the BST depends on the relative positions of the elements. For example, if there is an element with value 51 immediately next to 20 in one array, there must be no element between 20 and 51 in the other array for the trees to be equal (otherwise 20's right child would be that number, not 51).
I did try a few approaches:
- The naive approach: construct 2 trees and compare.
- I used an interesting variant where I'd partition the array into 2 (one smaller sub-array and one sub-array bigger than the pivot), and recursively pass the left array to the left child, and the other to the right. In-place and cheeky, but still O(N2).
- A friend tried applying the longest sub-sequence to it and finding it and then comparing, but that is incorrect.
- I was making inroads into maybe solving it with a LinkedHashMap, but I am having a tough time proving its correctness.
Help, and any hints towards solving this problem would be much appreciated.