Heap is a tree based data structure which follows relative ordering between nodes, specifically either the parent nodes are always greater than their children (called max-heap) or parent nodes are always lesser than their children (called min-heap). Checkout example in question #20 and #21.
Question #129: At what level(s) will the kth largest element be present? (Assume k<n)
Options:
- Levels 1 to k-1
- Levels 1 to last level
- Levels k-1 to last level
- Levels 1 to min(k-1, last level)
Solution: The correct answer is 4. kth largest element could be present in level 1, in that case all the larger elements will be present in the other subtree of the root node. Also, it could be present at level 2 as a child of 2nd largest element too. Similarly, it can be present at all levels upto k-1. Now, since heap is a full binary tree where all levels are completely filled except the last, there can only be log(n+1) levels. So depending upon where k is lesser than the last level or not, kth element could be present anywhere between levels 1 and min(k-1, last level).







