✏️
GitBook
  • Home
  • Projects
    • ORBI Group. Hotels Services
    • ORBI Group. Sales Support System
    • ORBI Group. Financial Management
    • ORBI Group. Client Cabinet
    • BP. Insurance management admin panel
    • Ciklum. Seaports fisheries containers tracking system
  • Higher Education
    • KNUTD (2018 - 2019)
    • School 42 (2017 - 2020)
  • FLG Preparation
    • Algorithms
      • Basics
        • Learn How To Learn
        • Algo task pattern
        • Space/time complexity
      • Two Pointers
        • Tasks
      • Fast and Slow Pointers
        • Tasks
      • Sliding Window
        • Tasks
      • Merge Intervals
        • Tasks
      • In-place Reversal of a Linked List
        • Tasks
      • Two Heaps
        • Tasks
      • K-Way Merge
        • Tasks
      • Top K Elements
        • Tasks
      • Subsets
        • Tasks
      • Modified Binary Search
        • Tasks
      • Greedy Techniques
        • Tasks
      • Backtracking
        • Tasks
      • Dynamic Programming
        • Tasks
        • 0/1 Knapsack Problem
      • Cyclic Sort
        • Tasks
      • Topological Sort
        • Tasks
      • Matrices
        • Tasks
      • Stacks
        • Tasks
    • Data Structures
      • Doubly Linked List
      • Stack
      • Queue
      • Heap
    • Frontend
    • Resources
  • Courses
    • Animations
    • JS Algorithms and Data Structures Course
      • Add Up To
      • Anagrams
      • Binary Search
      • Divide and Conquer
      • Frequency Counter
      • Sliding Window
      • Two Pointers
    • Nest.js
      • Logging
    • PostgreSQL
      • Sequelize
      • SUM
      • COUNT, DISTINCT (unique)
      • WHERE
      • AND, OR, BETWEEN
      • Practice 1
      • IN, NOT IN
      • ORDER BY
      • MIN, MAX, AVG
      • Practice 2
      • Pattern matching with LIKE
      • LIMIT, check for NULL (IS, IS NOT), GROUP BY, HAVING
      • UNION, INTERSECT, EXCEPT
      • Practice 3
      • INNER JOIN
      • LEFT, RIGHT JOIN
      • SELF JOIN
      • USING & NATURAL JOIN
      • AS
      • Practice 4
      • Practice 5. Subrequests
      • DDL - Data Definition Language
      • Practice 6. DDL
      • Primary & foreign keys
      • Check
      • Default
      • Sequences
      • INSERT
      • UPDATE, DELETE, RETURNING
      • Practice 7. DDL(2)
      • Проектирование БД
      • Нормальная форма (НФ)
      • Представление (View)
      • Создание представления
      • Обновляемые представления
      • Опция Check
      • Practice 8. Views
      • CASE WHEN
      • COALESCE & NULLIF
      • Practice 9. Logic
    • DevOps
      • Linux
        • File System
        • Command Line
        • Package Manager
        • VIM
        • Linux Accounts & Groups (Users & Permissions)
        • Pipes & Redirects
        • Shell / bash scripting
        • Environment Variables
      • Networking
      • SSH
      • Git for DevOps
      • Nexus. Artifact repository manager
      • Docker
      • Jenkins
  • Daily Log
    • 2023
Powered by GitBook
On this page

Was this helpful?

  1. FLG Preparation
  2. Data Structures

Heap

class Heap {
    constructor(comparator) {
        this.values = [];
        this.fn = comparator || Heap.minComparator;
    }

    size() {
        return this.values.length;
    }
    
    isEmpty() {
        return this.size() === 0;
    }

    pop() {
        return this.remove(this.values[0]);
    }

    peek() {
        return this.values[0];
    }

    add(value) {
        this.values.push(value);
        this.#bubbleUp(this.size() - 1);
    }

    remove(value) {
        const index = this.values.indexOf(value);
        // If value is not in heap, return
        if (index === -1) {
            return undefined;
        }
        if (index === this.size() - 1) {
            return this.values.pop();
        }
        this.#swap(index, this.size() - 1);
        const val = this.values.pop();
        this.#bubbleDown(this.#bubbleUp(index));
        return val;
    }

    #swap(index_1, index_2) {
        const temp = this.values[index_1];
        this.values[index_1] = this.values[index_2];
        this.values[index_2] = temp;
    }

    #compare(index_1, index_2) {
        return this.fn(this.values[index_1], this.values[index_2]);
    }

    #bubbleUp(index) {
        // If index is 0, we are at the root
        if (index === 0) {
            return index;
        }
        const parentIndex = Math.floor((index - 1) / 2);
        if (this.#compare(parentIndex, index)) {
            this.#swap(parentIndex, index);
            this.#bubbleUp(parentIndex);
        }
        return index;
    }

    #bubbleDown(index) {
        const leftChildIndex = 2 * index + 1;
        const rightChildIndex = 2 * index + 2;
        let largestIndex = index;
        if (leftChildIndex < this.size() && this.#compare(largestIndex, leftChildIndex)) {
            largestIndex = leftChildIndex;
        }
        if (rightChildIndex < this.size() && this.#compare(largestIndex, rightChildIndex)) {
            largestIndex = rightChildIndex;
        }
        if (largestIndex !== index) {
            this.#swap(index, largestIndex);
            this.#bubbleDown(largestIndex);
        }
        return index;
    }
}

Heap.minComparator = (a, b) => a > b;
Heap.maxComparator = (a, b) => a < b;

Operation

Time Complexity

size

O(1)

isEmpty

O(1)

pop

O(log n)

peek

O(1)

add

O(log n)

remove

O(log n)

#swap

O(1)

#compare

O(1) // depends on the implementation

#bubbleDown

O(log n)

#bubbleUp

O(log n)

PreviousQueueNextFrontend

Last updated 2 years ago

Was this helpful?