Microsoft Interview Question
Software Engineer in TestsThis seems to be the best out of the solutions posted above. At each node, store the number of nodes in the left sub tree and the number of nodes in the right sub tree!
Also store the depth of the left tree and depth of the right tree.
An inorder traversal at any point will give the pages of the book in order. Now, while inserting the precise point of insertions is known. i.e while inserting pg 15 we have to reach the node which has a cumulative of 14 pages. Insert the node. Now use balancing techniques to rebalance the tree
Maybe priority queue (min heap for example), so you could easily change page number (priority). It will take lg*N time to change page priority.
think about adding pages randomly to the book either at the end or in the middle.. suppose there are 20 pages and we insert an extra page after 15 so the ordering of page 15-20 changes to 16-21. Is binary search tree or Linked list an option in such case? what about eliminating duplicates and reordering the pages? if it is just about adding more pages at the end is it easier in BST (lgn) and it takes O(1) in Linked list (adding to the tail), max heap also sounds good..
@ rash, How come BST time complexity O(log n ).
Let us say page nos
1 2 3 4 5
add a new page at stating of the book, then you have to modify all page nos .
1 2 3 4 5 6
Adding a new page at the starting of the book ,time complexity O(n). you have added n new pages at the staring then total time complexity O(n^2 ).
Use ArrayList where any page can be accessed in o(1)and if you add randon pages the arraylist memeory increased dynamically
I think LinkedList would be good, as we can add a page with the worst time of O(n), the insertion will be easy in ArrayList (or) tree but the followup (incrementing rest of the entities) will be painful.
Why not a balanced binary tree? To search for a place to insert and to insert in tree it only takes O(log n) ! Once the book is final, in order traversal can assign page numbers.
- ashishkaila@hotmail.com November 22, 2011