You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tech-interview-handbook/contents/algorithms/heap.md

2.9 KiB

id title toc_max_heading_level
heap Heap 2

Introduction

A heap is a specialized tree-based data structure which is a complete tree that satisfies the heap property.

  • Max heap - In a max heap the value of a node must be greatest among the node values in its entire subtree. The same property must be recursively true for all nodes in the tree.
  • Min heap - In a min heap the value of a node must be smallest among the node values in its entire subtree. The same property must be recursively true for all nodes in the tree.

In the context of algorithm interviews, heaps and priority queues can be treated as the same data structure. A heap is a useful data structure when it is necessary to repeatedly remove the object with the highest (or lowest) priority, or when insertions need to be interspersed with removals of the root node.

Implementations

Language API
C++ std::priority_queue
Java java.util.PriorityQueue
Python heapq
JavaScript N/A

Time complexity

Operation Big-O
Finx max/min O(1)
Insert O(log(n))
Remove O(log(n))
Heapify (create a heap out of given array of elements) O(n)

Learning resources

Techniques

Mention of k

If you see a top or lowest k being mentioned in the question, it is usually a signal that a heap can be used to solve the problem, such as in Top K Frequent Elements.

If you require the top k elements use a Min Heap of size k. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds k, remove the minimum element, that will guarantee that you have the k largest elements.

import AlgorithmCourses from '../_courses/AlgorithmCourses.md'