Posts

Showing posts with the label Heap

Kth Largest Element in an Array @LeetCode

PROBLEM : Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 = k = array's length. -------------------------------------------------------------------------------- SIMPLE c++ IMPLEMENTATION : -------------------------------------------------------------------------------- class Solution { public:     int findKthLargest(vector<int>& nums, int k) {         priority_queue<int> pq(nums.begin(),nums.end()) ;         k-- ;                 while(k--)             pq.pop() ;         return pq.top() ;     } }; --------------------------------------------------------------------------------

Does array represent Heap

PROBLEM : Given an array, the task is to check if the given array represents a Binary Max-Heap. Examples: Input:  A[] = {90, 15, 10, 7, 12, 2} Output: 1 The given array represents below tree        90      /    \    15      10   /  \     /  7    12  2 The tree follows max-heap property as every node is greater than all of its descendants. Input:  A[] = {9, 15, 10, 7, 12, 11} Output: 0 The given array represents below tree        9      /    \    15      10   /  \     /  7    12  11 The tree doesn't follows max-heap property 9 is smaller than 15 and 10, and 10 is smaller than 11. Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The firs...

Operations on Binary Min Heap

PROBLEM : Your task is to implement the three methods insertKey,  deleteKey,  and extractMin on a Binary Min Heap Example The first line of the input contains an integer 'T' denoting the number of test cases. Then T test cases follow. First line of each test case contains an integer Q denoting the number of queries . A Query Q is of 3 Types 1.  1  x  (a query of this type means to insert an element in the min heap with value x ) 2.  2  x  (a query of this type means to remove an element at position x from the min heap) 3. 3  (a query like this removes the min element from the min heap and prints it ). The second line of each test case contains Q queries seperated by space. Output: The output for each test case will  be space separated integers having -1  if the heap is empty else the min element of the heap from the stack. You are required to complete the 3 methods insertKey which takes one argument the value to be...