![]() |
VOOZH | about |
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap.
Examples:
Input: N = 2
👁 Image
Output: 1 1
Explanation:
There is only one maximum binary heap with the nodes {1, 2}:
In the above tree, maximum leaf node value = 1.
Therefore, the largest element is 1 and the smallest element is also 1.Input: N = 3
👁 Image
Output: 2 2
Explanation:
There are two possible maximum binary heaps with the nodes {1, 2, 3}:
👁 Image
The maximum leaf nodes of first and second heaps are 2 and 2 respectively.
Therefore, the largest element is 2 and the smallest element is also 2.
Naive Approach: The simplest approach is to generate all possible max binary heaps that can be formed from first N natural numbers and keep track of the smallest and largest leaf node values among all the maximum leaf nodes in all the heaps.
Time Complexity: O(N*N!)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
Follow the steps below to solve the problem:
numberOfleaves = (N- N/2).
D = ceil(log2(N+1))-1
Below is the implementation of the above approach:
1 1
Time Complexity: O(log(N))
Auxiliary Space: O(1)