QHEAP1

Sort by

recency

|

38 Discussions

|

  • + 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.

  • + 0 comments

    My Java solution

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
    static class MyHeap {
        private long[] items;
        private int capacity = 10;
        private int size;
    
        private int leftIndex(int index) {
            return index * 2 + 1;
        }
    
        private int rightIndex(int index) {
            return index * 2 + 2;
        }
    
        private int parentIndex(int index) {
            return (index - 1) / 2;
        }
    
        private long getLeftNode(int index) {
            return items[leftIndex(index)];
        }
    
        private long getRightNode(int index) {
            return items[rightIndex(index)];
        }
    
        private long getParentNode(int index) {
            return items[parentIndex(index)];
        }
    
        private boolean hasLeftNode(int index) {
            return leftIndex(index) < size;
        }
    
        private boolean hasRightNode(int index) {
            return rightIndex(index) < size;
        }
    
        private boolean hasParentNode(int index) {
            return parentIndex(index) >= 0;
        }
    
        public MyHeap() {
            this.size = 0;
            this.items = new long[capacity];
        }
    
        public void add(int item) {
            checkCapacity();
            this.items[size] = item;
            this.size += 1;
            heapifyUp();
        }
    
        public long poll() {
            long head = items[0];
            swap(0, size - 1);
            size -= 1;
            heapifyDown();
    
            return head;
        }
    
        public long peek() {
            long item = items[0];
            return item;
        }
    
        public void remove(int item) {
            int index = search(item);
            swap(index, size - 1);
            size -= 1;
            heapifyDown(index);
        }
    
        public int search(int item) {
            for (int i = 0; i < size; i++) {
                if (item == items[i])
                    return i;
            }
    
            return -1;
        }
    
        private void checkCapacity() {
            if (size >= capacity) { // grow
                this.capacity *= 2;
                long[] newItems = new long[capacity];
                for (int i = 0; i < size; i++) {
                    newItems[i] = items[i];
                }
                this.items = newItems;
            }
        }
    
        private void swap(int indexOne, int indexTwo) {
            long tmp = this.items[indexOne];
            this.items[indexOne] = this.items[indexTwo];
            this.items[indexTwo] = tmp;
        }
    
        private void heapifyUp() {
            int index = size - 1;
            while (hasParentNode(index) && getParentNode(index) > items[index]) {
                swap(parentIndex(index), index);
                index = parentIndex(index);
            }
        }
    
        private void heapifyDown() {
            heapifyDown(0);
        }
    
        private void heapifyDown(int currentIndex) {
    
            while (hasLeftNode(currentIndex)) {
                int smallerChildIndex = leftIndex(currentIndex);
                if (hasRightNode(currentIndex) && getRightNode(currentIndex) < getLeftNode(currentIndex)) {
                    smallerChildIndex = rightIndex(currentIndex);
                }
    
                if (items[smallerChildIndex] < items[currentIndex]) {
                    swap(currentIndex, smallerChildIndex);
                }
    
                currentIndex = smallerChildIndex;
            }
        }
    
    }
    
    public static void main(String[] args) throws IOException {
    
        Scanner scanner = new Scanner(System.in);
    
        // PriorityQueue<Integer> pq = new PriorityQueue<>();
        Solution.MyHeap pq = new Solution.MyHeap();
        int Q = scanner.nextInt();
        while (Q-- > 0) {
            int op = scanner.nextInt();
            switch (op) {
                case 1: // add
                    pq.add(scanner.nextInt());
                    break;
                case 2: // delete
                    pq.remove(scanner.nextInt());
                    break;
                default: // print
    
                    System.out.println(pq.peek());
    
            }
        }
    
        scanner.close();
    }
    }