Leftist Heap - Problem

A leftist heap is a priority queue implemented as a binary tree where the heap property is maintained and the tree is leftist - meaning for every node, the rank of the left child is greater than or equal to the rank of the right child.

The rank of a node is defined as the length of the shortest path from that node to any external node (null). An external node has rank 0.

Implement a LeftistHeap class that supports:

  • insert(value) - Insert a value into the heap
  • deleteMin() - Remove and return the minimum value
  • merge(other) - Merge with another leftist heap
  • isEmpty() - Check if heap is empty
  • getMin() - Get minimum value without removing it

All operations should run in O(log n) time complexity using rank-based merging.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["insert", 3], ["insert", 7], ["getMin"], ["deleteMin"], ["isEmpty"]]
Output: [3, 3, false]
💡 Note: Insert 3 and 7, getMin returns 3, deleteMin removes and returns 3, isEmpty returns false since 7 remains
Example 2 — Multiple Inserts and Deletes
$ Input: operations = [["insert", 5], ["insert", 2], ["insert", 8], ["deleteMin"], ["deleteMin"], ["getMin"]]
Output: [2, 5, 8]
💡 Note: Insert 5, 2, 8. DeleteMin twice returns 2 then 5. GetMin shows remaining minimum is 8
Example 3 — Empty Heap Operations
$ Input: operations = [["isEmpty"], ["insert", 10], ["deleteMin"], ["isEmpty"]]
Output: [true, 10, true]
💡 Note: Initially empty (true), insert 10, deleteMin returns 10, now empty again (true)

Constraints

  • 1 ≤ operations.length ≤ 1000
  • -104 ≤ value ≤ 104
  • All operations are valid (no deleteMin on empty heap)

Visualization

Tap to expand
INPUTLeftist Heap Structure3rank=27r=28r=11215Operations: insert, deleteMinmerge, getMin, isEmptyALGORITHMRank-Based Merging11. Compare roots22. Merge with right child33. Swap if needed44. Update ranksKey PropertyLeft rank ≥ Right rankRESULTOptimal PerformanceTime ComplexityO(log n)All operationsSpace ComplexityO(n)Node storageBenefits:• Efficient merge operations• Logarithmic all operations• Self-balancing structureKey Insight:The leftist property ensures merge operations follow the right spine,which is guaranteed to be at most log n deep, making all operations efficient.TutorialsPoint - Leftist Heap | Rank-Based Merging
Asked in
Google 25 Microsoft 18 Facebook 15 Amazon 12
18.5K Views
Medium Frequency
~35 min Avg. Time
856 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