{"id":22192348,"url":"https://github.com/mzusin/heap","last_synced_at":"2025-03-24T20:44:59.526Z","repository":{"id":203999484,"uuid":"710878599","full_name":"mzusin/heap","owner":"mzusin","description":"Typescript implementation of minimum and maximum heap (priority queue).","archived":false,"fork":false,"pushed_at":"2023-11-10T18:48:53.000Z","size":146,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-30T01:18:24.175Z","etag":null,"topics":["binary-heap","heap","heapsort","heapsort-algorithm","max-heap","min-heap","priority-queue","top-k-element"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mzusin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-10-27T16:22:07.000Z","updated_at":"2023-11-10T17:19:34.000Z","dependencies_parsed_at":"2023-11-10T16:44:34.949Z","dependency_job_id":null,"html_url":"https://github.com/mzusin/heap","commit_stats":null,"previous_names":["mzusin/heap"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mzusin%2Fheap","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mzusin%2Fheap/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mzusin%2Fheap/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mzusin%2Fheap/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mzusin","download_url":"https://codeload.github.com/mzusin/heap/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245351761,"owners_count":20601090,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binary-heap","heap","heapsort","heapsort-algorithm","max-heap","min-heap","priority-queue","top-k-element"],"created_at":"2024-12-02T12:22:23.644Z","updated_at":"2025-03-24T20:44:59.506Z","avatar_url":"https://github.com/mzusin.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Heap (Binary Heap, Priority Queue)\n\nTypescript implementation of minimum and maximum heap (priority queue).\n\n## Documentation\n\n```ts\nexport const heap: (type: HeapType, values?: number[]) =\u003e IHeap;\nexport const maxHeap: (values?: number[]) =\u003e IHeap;\nexport const minHeap: (values?: number[]) =\u003e IHeap;\nexport const heapsort: (values: number[], isAsc?: boolean) =\u003e void;\n\n// O(N log N)\nexport const findTopKLargestElementsNaive: (values: number[], k: number) =\u003e number[];\nexport const findTopKSmallestElementsNaive: (values: number[], k: number) =\u003e number[];\n\n// O(K log N)\nexport const findTopKLargestElementsNaive1: (values: number[], k: number) =\u003e number[];\nexport const findTopKSmallestElementsNaive1: (values: number[], k: number) =\u003e number[];\n\n// O(N log K)\nexport const findTopKLargestElements: (values: number[], k: number) =\u003e number[];\nexport const findTopKSmallestElements: (values: number[], k: number) =\u003e number[];\n\n// O(N log N)\nexport const findKthLargestValueNaive: (values: number[], k: number) =\u003e number|null;\nexport const findKthSmallestValueNaive: (values: number[], k: number) =\u003e number|null;\n\n// O(K log N)\nexport const findKthLargestValueNaive1: (values: number[], k: number) =\u003e number | null;\nexport const findKthSmallestValueNaive1: (values: number[], k: number) =\u003e number | null;\n\n// O(N log K)\nexport const findKthLargestValue: (values: number[], k: number) =\u003e number | null;\nexport const findKthSmallestValue: (values: number[], k: number) =\u003e number | null;\n```\n\n| Method    | Description                                                                                                                                                                                                                            |                                 |\n|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------|\n| add()     | Adds a single element with the specified value to the heap while maintaining the appropriate heap property. It returns the new maximum element in a Max Heap or the new minimum element in a Min Heap, or `null` if the heap is empty. | add: (val: number) =\u003e number    |null          |\n| addList() | Adds an array of elements to the heap and maintains the appropriate heap property after each addition.                                                                                                                                 | addList(values: number[]): void |\n| poll ()   | Removes and returns the root element of the heap, which is either the maximum (in a Max Heap) or the minimum (in a Min Heap) element.                                                                                                  | poll(): number                  | null                      |\n| peek()    | Returns the root element of the heap, which is either the maximum (in a Max Heap) or the minimum (in a Min Heap) element, without removing it from the heap.                                                                           | peek(): number                  | null                      |\n| size()    | Returns the number of elements currently present in the heap.                                                                                                                                                                          | size(): number                  |\n| isLeaf()  | Checks if the element at the specified index in the heap is a leaf node.                                                                                                                                                               | isLeaf(index: number): boolean  |\n| values()  | It returns an array containing all the elements in the heap, but does not guarantee a specific order or structure within the array, as the heap's structure may not be preserved in the returned array.                                | values: () =\u003e number[];         |\n\n\n## maxHeap\n\n```ts\nimport { maxHeap } from 'mz-heap';\n\nconst heap = maxHeap();\n\nheap.add(5);\nheap.add(3);\nheap.addList([7, 10, 2]);\n\nconsole.log(heap.peek());\nconsole.log(heap.size());\nconsole.log(heap.isLeaf(1));\n\nheap.poll();\nheap.poll();\n```\n\n## minHeap\n\n```ts\nimport { minHeap } from 'mz-heap';\n\nconst heap = minHeap();\n\nheap.add(5);\nheap.add(3);\nheap.addList([7, 10, 2]);\n\nconsole.log(heap.peek());\nconsole.log(heap.size());\nconsole.log(heap.isLeaf(1));\n\nheap.poll();\nheap.poll();\n```\n\n## Heap\n\n- Heap is a type of **binary tree**.\n- This is a **complete binary tree** i.e. it is filled strictly from left to right, it is impossible for there to be a branch on the right and not a branch on the left. Reverse case can be only at the very end of the tree.\n- **Min heap** - the minimum value on top, and for each node its children \u003e= parent node.\n- **Max heap** - the maximum value on top, and for each node its children \u003c= parent node.\n- To **add** a node, add it to the end of the tree, and then correct the condition (**heapify**).\n- To **delete** a node, take the last node and put it instead of root, and then correct the condition (**heapify**).\n\n## Usage\n\n1. Priority queue.\n2. To find min/max in O(1), while removing and adding in O(log n).\n3. [Heap Sort](https://leetcode.com/explore/learn/card/heap/645/applications-of-heap/4030/)\n4. The Top-K problem.\n5. The K-th element.\n\n## Space and Time Complexity\n\n- Construct a Heap\n  - Time complexity: **O(N)**\n  - Space complexity: **O(N)**\n\n- Insert an element\n    - Time complexity: **O(log N)**\n    - Space complexity: **O(1)**\n\n- Get the top element\n    - Time complexity: **O(1)**\n    - Space complexity: **O(1)**\n\n- Delete the top element\n    - Time complexity: **O(log N)**\n    - Space complexity: **O(1)**\n\n- Get the size of a Heap\n    - Time complexity: **O(1)**\n    - Space complexity: **O(1)**\n\n## HeapSort\n\n**Pros**\n\n- No extra memory space is required to work, unlike the Merge Sort or recursive Quick Sort.\n- The algorithm is efficient. Performance is optimal. This implies that no other sorting algorithms can perform better in comparison.\n- The Heap sort algorithm exhibits consistent performance. This means it performs equally well in the best, average and worst cases.\n- Quicksort has a disadvantage there as its worst case time complexity of O(n^2). Mergesort has the disadvantage that its memory complexity is O(n) whereas Heapsort is O(1).\n- [More](https://stackoverflow.com/questions/18163414/in-which-cases-do-we-use-heapsort)\n\n**Cons**\n\n- **It is unstable sort** - A stable sort maintains the relative order of items that have the same key. i.e the way they are present in initial array. Heapsort is unstable sort. It might rearrange the relative order. \n- [Expensive constant factors](https://stackoverflow.com/questions/8311090/why-not-use-heap-sort-always)\n- Quicksort and mergesort are both easier to parallelize than heapsort.\n- Cache inefficient.\n- Not really adaptive (Doesn't get faster if given somewhat sorted array).\n\n----------------\n\n### Leetcode Questions\n- [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmzusin%2Fheap","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmzusin%2Fheap","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmzusin%2Fheap/lists"}