Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs.
Question - 2
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water
(blue section) are being trapped.
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at the end of the array.
input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9]
output should be [9, -7, 8, -3, 5, -1, 2, 4, 6]
Note - A minor optimization in space complexity can be achieved, by using implementing inorder traversal of Binary Search Tree iteratively and using stack to store each branch of a Tree. However, since worst case complexity still remains same, this isn't really required.
Implementation of above idea in C++.
A straightforward solution is to simply store all positives in one array, all negatives in another array and eventually combine them one by one into final array. However, this results in O(N) time which is optimal, but O(N) space which is good, but not optimal.
So how can we achieve optimal space and time complexity solutions?
Turns out there are multiple equally interesting solutions!
Solution 1 - Using Dutch Flag Algorithm
Solution 2 - Using Pivot idea from Quicksort The idea is to use 0 as a pivot element and make one pass of the partition process. The resultant array will contain all positive integers at the end of the array and all negative integers at the beginning. Then swap alternate negative elements from the next available positive element until the end of the array is reached, or all negative or positive integers are exhausted just like solution above.
Sample Illustration
In Problem 3, solution 1
If we have less negative numbers than positive numbers, then we would have to start swapping from the 0th index, otherwise we would not be able maximise the prefix where this condition (ai * ai-1 < 0 ) holds.