> For the complete documentation index, see [llms.txt](https://interviews.woojiahao.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://interviews.woojiahao.com/data-structures/graphs/trees/heaps.md).

# Heaps

{% hint style="info" %}
Heaps can be implemented as trees under the hood, but some are also implemented using arrays. I have chosen to stick to the implementation I was taught and park heaps under Trees
{% endhint %}

## Runtime analysis

1. Find min/max: $$O(1)$$
2. Insert: $$O(\log n)$$
3. Remove: $$O(\log n)$$
4. Heapify: $$O(n)$$

## Techniques

### Max heaps

In Python, `heapq` is defaults to using a min heap. This might not be what you want by default. The only way to make `heapq` work as a max heap is by inverting the values inserted

### K-smallest/largest

K-smallest implies using a k-sized max heap, removing the maximum element if the size becomes `> k`

K-largest implies using a k-sized min heap instead

### Using quick select instead

Sometimes, the information required from a k-sized heap can be replicated by using [Quick Select](/algorithms/quick-select.md). The benefit of doing so is that the runtime can be reduced to $$O(n)$$ whereas with heaps, it would be $$O(n \log n)$$

### Finding the median of data

Simulate the median by having a max heap for the elements to the left of the median and a min heap for the elements to the right of the median


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://interviews.woojiahao.com/data-structures/graphs/trees/heaps.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
