Sobes.tech
Junior — Middle

What data structure is preferable for quickly retrieving the maximum element with rare insertions?

sobes.tech AI

Answer from AI

For the task of quickly extracting the maximum element with rare insertions, it is preferable to use the data structure Max-Heap.

Explanation:

  • Insertion into the heap takes O(log n) time.
  • Extracting the maximum is O(1) for accessing the root and O(log n) for removal.

If insertions are indeed rare and maximum extractions are frequent, then Max-Heap provides a good balance between insertion speed and quick access to the maximum.

In Java, you can use PriorityQueue with a comparator for maximum:

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

// Insertion
maxHeap.offer(10);
maxHeap.offer(5);

// Getting the maximum
int max = maxHeap.peek();