Samsung Interview Question
Senior Software Development EngineersCountry: United States
Interview Type: In-Person
I think the efficiency of the above algorithm is not O(log N).
There is are two recursive calls.
1) the function sizeOfBST is O(N log(N)) since it traverses the entire tree for each half.
2) the function kSmallestInBST is O(log N) since it goes to each half of the tree.
and point 1) is called as many times as 2) and hence
Efficiency is O(n * logn * logn)
Let me know if I am wrong. I didnt do detail analysis, just a glance of the code.
I think, you are not saving anything here apart from some constant save,
Calculation of number of nodes on the left subtree is O(number of elements of left subtree), which is equal to accessing the value of the element, i think in every case it is going to be O(n) more appropriately O(k)
Can be done by Inorder traversal technique, which will result in O(N) time.
Another Approach:
Let each node in the BST have a field that returns the number of elements in its left and right subtree. Let the left subtree of node T contain only elements smaller than T and the right subtree only elements larger than or equal to T.
Now, suppose we are at node T:
k == num_elements(left subtree of T), then the answer we're looking for is the value in node T
k > num_elements(left subtree of T) then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.
This is O(log N) on average (assuming a balanced tree)
- R@M3$H.N September 24, 2014