Heap Implementation - Problem

Implement both a min-heap and max-heap data structure with the following operations:

Min-Heap Operations:

  • insert(value) - Insert a value into the min-heap
  • extractMin() - Remove and return the minimum element
  • getMin() - Return the minimum element without removing it

Max-Heap Operations:

  • insert(value) - Insert a value into the max-heap
  • extractMax() - Remove and return the maximum element
  • getMax() - Return the maximum element without removing it

Your task is to process a series of operations and return the final state of both heaps as arrays.

The input will be an array of operations, where each operation is represented as [type, heap, value]:

  • type: 0 = insert, 1 = extract, 2 = get
  • heap: 0 = min-heap, 1 = max-heap
  • value: the value to insert (only for insert operations)

Input & Output

Example 1 — Basic Operations
$ Input: operations = [[0,0,5],[0,1,10],[0,0,3],[1,0],[0,1,8]]
Output: [[5],[10,8]]
💡 Note: Insert 5 into min-heap, insert 10 into max-heap, insert 3 into min-heap, extract min (removes 3), insert 8 into max-heap. Final state: min-heap=[5], max-heap=[10,8]
Example 2 — Multiple Extractions
$ Input: operations = [[0,0,1],[0,0,4],[0,0,2],[1,0],[1,0]]
Output: [[4],[]]
💡 Note: Insert 1,4,2 into min-heap → [1,4,2]. Extract min twice → removes 1, then 2. Final min-heap=[4], max-heap=[]
Example 3 — Empty Operations
$ Input: operations = []
Output: [[],[]]
💡 Note: No operations performed, both heaps remain empty

Constraints

  • 0 ≤ operations.length ≤ 1000
  • operations[i].length is 2 or 3
  • 0 ≤ operations[i][0] ≤ 2 (operation type)
  • 0 ≤ operations[i][1] ≤ 1 (heap type)
  • -1000 ≤ operations[i][2] ≤ 1000 (value for insert operations)

Visualization

Tap to expand
INPUTOperations Array:[0,0,5] → insert 5 to min-heap[0,1,10] → insert 10 to max-heap[0,0,3] → insert 3 to min-heap[1,0] → extract from min-heapOperation Types:0=insert, 1=extract, 2=getheap: 0=min, 1=maxALGORITHM1Build heap structure2Insert: add to end, bubble up3Extract: move last to root, bubble down4Maintain heap property: parent ≤ childrenMin-Heap Tree:35Array: [3,5]RESULTFinal Heap States:Min-Heap5[5]Max-Heap108[10,8]Output: [[5],[10,8]]✓ Min element (3) extracted✓ Heap properties maintainedKey Insight:Heaps use array-based binary trees where parent-child relationships are maintained throughindex arithmetic (parent at i/2, children at 2i+1 and 2i+2), enabling O(log n) operations.TutorialsPoint - Heap Implementation | Binary Heap with Heapify Operations
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen