QHEAP1

Sort by

recency

|

39 Discussions

|

  • + 0 comments
    from heapq import heappush, heappop
    
    h, p = [], set()
    for s in [input().split(' ') for _ in range(int(input()))]:
        if s[0] == '1':
            p.add(int(s[1])), heappush(h, int(s[1]))
        elif s[0] == '2':
            p.discard(int(s[1]))
        elif s[0] == '3':
            while h[0] not in p:
                heappop(h)
            print(h[0])
    
  • + 0 comments

    Here is hackerrank QHEAP1 problem solution in Python, Java, C++, C and javascript

  • + 0 comments

    In JAVA8 :

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            PriorityQueue<Integer> minHeap = new PriorityQueue<>(); 
            int i = 0, Q = Integer.parseInt(br.readLine().trim());
            while (i++ < Q) {
                String[] input = br.readLine().split(" ");
                switch(Integer.parseInt(input[0])){
                    case 1 :{
                        minHeap.offer(Integer.parseInt(input[1]));
                        break;
                    }
                    case 2 :{
                        minHeap.remove(Integer.parseInt(input[1]));
                        break;
                    }
                    case 3 :{
                        System.out.println(minHeap.peek());
                        break;
                    }
                    default :{
                        System.out.println("Invalid !");
                    }
                }
            }
        }
    }
    
  • + 0 comments
    class MinHeap:
        def __init__(self):
            self.heap = []
            
        def add(self, v):
            self.heap.append(v)
            self.__sift_up__(len(self.heap)-1)
            
        def delete(self, v):
            h = self.heap
            if h:
                try:
                    idx = self.heap.index(v)
                    h[idx], h[-1] = h[-1], h[idx]
                    h.pop()
                    if idx < len(h):
                        self.__sift_down__(idx)
                        self.__sift_up__(idx)
                except ValueError:
                    ...
                    
        def print_min(self):
            if self.heap:
                print(self.heap[0])
                
                
        def __sift_up__(self, idx):
            # compare and swap with parent upwards repeatedly: (idx-1)//2
            h = self.heap
            item = h[idx]
            while idx > 0:
                parent_idx = (idx-1)//2
                if item < h[parent_idx]:
                    h[idx] = h[parent_idx]
                    idx = parent_idx
                else:
                    break
            h[idx] = item
            
        def __sift_down__(self, idx):
            # compare and swap with children downwards repeatedly:
            h = self.heap
            size = len(h)
            item = h[idx]
            while True:
                l_idx, r_idx, min_idx = 2*idx+1, 2*idx+2, idx
                if l_idx < size and h[l_idx] < item:
                    min_idx = l_idx
                if r_idx < size and h[r_idx] < h[min_idx]:
                    min_idx = r_idx
                if min_idx != idx:
                    h[idx] = h[min_idx]
                    idx = min_idx
                else:
                    break
            h[idx] = item
        
    
    # Initialize the min-heap
    minHeap = MinHeap()
    
    # Number of operations
    num_of_queries = int(input())
    
    # Execute operations
    for _ in range(num_of_queries):
        op = input().split()
        op_code = op[0]
        if op_code == '1':
            minHeap.add(int(op[1]))
        elif op_code == '2':
            minHeap.delete(int(op[1]))
        elif op_code == '3':
            minHeap.print_min()
    
  • + 0 comments

    When you delete the root, you replace it with the last element, then perform heapifyDown, if the new Root is greater than either children.

    But when you have to delete any arbitrary element, after replacing it with the last element, dont you need to take care of both the conditions below? 1) Heapify up - If the element is less than the parent 2) Heapify Down - If the element is greater than either children.

    But the editorial only does a Heapify Down operation during deletion?

    For instance, consider the tree :- 10, 20, 16, 40, 50, 18, 17, 80, 85, 55, 56, 19. If you want to delete node 40, you replace it with the last element i.e. 19. Now a heapify down operation wont restore the heap property. You will need to do a heapify up operation and this is not covered in the Editorial code. Wanted to check if my understanding is correct.