BackhardHeapSwiggyMeta

Bitmask Energy Vector Architect Solution

Problem Statement

You are given an integer N and an array A of N distinct integers. Construct a min‑max priority heap that supports two operations in O(log N) time: extractMin() returns and removes the smallest element, and extractMax() returns and removes the largest element. Starting with an empty result list, repeatedly perform extractMin() followed by extractMax() while the heap still contains elements (if only one element remains, perform only extractMin()). Output the sequence of values removed, in the exact order they were extracted.

Input: The first line contains a single integer N (1 ≤ N ≤ 2·10⁵). The second line contains N space‑separated integers A[i] (|A[i]| ≤ 10⁹). All A[i] are distinct.

Output: Print the extracted values separated by a single space.

The task tests the ability to implement a min‑max heap and to use it to produce the alternating min‑max ordering of the given multiset.

Example 1
Input
7 4 1 9 3 8 2 6
Output
1 9 2 8 3 6 4

Explanation: Build a min‑max heap from the 7 numbers. First extractMin() yields 1. Heap now contains {2,3,4,6,8,9}. Next extractMax() yields 9. Heap now {2,3,4,6,8}. Continue: extractMin() → 2, extractMax() → 8, extractMin() → 3, extractMax() → 6, only 4 remains so a final extractMin() → 4. The removal order is 1 9 2 8 3 6 4.

Example 2
Input
4 -5 10 0 7
Output
-5 10 0 7

Explanation: Initial heap: {-5,0,7,10}. extractMin() → -5, heap {0,7,10}. extractMax() → 10, heap {0,7}. extractMin() → 0, heap {7}. Only one element left, so final extractMin() → 7. Result: -5 10 0 7.

Example 3
Input
1 42
Output
42

Explanation: With a single element, the algorithm performs only one extractMin(), returning 42.

Constraints

  • 1 <= N <= 200000
  • All A[i] are distinct
  • -10^9 <= A[i] <= 10^9
  • The algorithm must run in O(N log N) time and O(N) additional memory
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Bitmask Energy Vector Architect — Problem Statement & Solution Guide

HeapHardMin-Max Priority Heap Queue
TimeO(N log N) for the full extraction sequence (O(N) build + O(N log N) for N/2 pairs of extracts)
|
SpaceO(N)

Problem Description

You are given an integer N and an array A of N distinct integers. Construct a min‑max priority heap that supports two operations in O(log N) time: extractMin() returns and removes the smallest element, and extractMax() returns and removes the largest element. Starting with an empty result list, repeatedly perform extractMin() followed by extractMax() while the heap still contains elements (if only one element remains, perform only extractMin()). Output the sequence of values removed, in the exact order they were extracted.

Input: The first line contains a single integer N (1 ≤ N ≤ 2·10⁵). The second line contains N space‑separated integers A[i] (|A[i]| ≤ 10⁹). All A[i] are distinct.

Output: Print the extracted values separated by a single space.

The task tests the ability to implement a min‑max heap and to use it to produce the alternating min‑max ordering of the given multiset.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bitmask Energy Vector Architect"

hard

WHY DOES IT MATTER?

The min‑max heap pattern enables bidirectional priority access without duplicating data, a frequent requirement in simulations, stock order books, and real‑time matchmaking where both extremes must be processed efficiently.

OPTIMIZATION CHALLENGE

The key insight is to treat the tree levels alternately as min‑levels and max‑levels, allowing a single structure to answer both extreme queries while only traversing a single root‑to‑leaf path during updates.

REAL-WORLD CONNECTION

Think of a double‑ended priority queue as a two‑sided elevator: passengers can board from the bottom (min) or the top (max) floor, and the elevator shaft (the heap) moves them up or down with the same effort regardless of direction.

When coding, implement helper functions like isMinLevel(index) = (floor(log2(index)) % 2 == 0) to cleanly separate min and max logic; this reduces bugs and makes the percolate steps easier to reason about.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log N) for the full extraction sequence (O(N) build + O(N log N) for N/2 pairs of extracts)
💾 Space:O(N)

Core Theory — Why This Approach?

A min‑max heap is a complete binary tree that simultaneously satisfies the min‑heap property on even levels and the max‑heap property on odd levels. This dual ordering guarantees that the root holds the global minimum, while one of its children (the first level) holds the global maximum, allowing both extractMin and extractMax in O(log N). Naïve solutions—such as maintaining two separate heaps or scanning the entire array for each extraction—either double the memory overhead or degrade to O(N) per operation, which is unacceptable for large N. The optimal paradigm leverages the structural invariants of the min‑max heap: during insertion or deletion, we percolate the element up or down through alternating min and max levels, fixing violations in O(log N) time while preserving the complete‑tree shape.

Interview Questions on This Problem

Q1How does a min‑max heap differ from maintaining two separate min‑heap and max‑heap structures for the same data set?

A min‑max heap stores each element once and uses level parity to enforce both min and max ordering, achieving O(log N) operations with O(N) space. Two separate heaps duplicate elements, requiring extra O(N) space and complex synchronization to keep them consistent after deletions.

Q2Explain the percolate‑down procedure for extractMax in a min‑max heap.

After removing the max (found at one of the root’s children), we replace it with the last element, then percolate down on a max level: compare with the largest among its grandchildren, swap if needed, and then continue percolating down on the corresponding min level to restore the alternating invariants.

Q3Why does the min‑max heap guarantee O(log N) time for both extractMin and extractMax, even though the max is not at the root?

The max resides at one of the root’s children, which are at depth 1. Accessing it is O(1). The subsequent percolate‑down traverses at most the height of the tree (⌊log₂N⌋) while fixing violations only along a single path, yielding O(log N) time.

Examples

Example 1

Input

7
4 1 9 3 8 2 6

Output

1 9 2 8 3 6 4

Explanation: Build a min‑max heap from the 7 numbers. First extractMin() yields 1. Heap now contains {2,3,4,6,8,9}. Next extractMax() yields 9. Heap now {2,3,4,6,8}. Continue: extractMin() → 2, extractMax() → 8, extractMin() → 3, extractMax() → 6, only 4 remains so a final extractMin() → 4. The removal order is 1 9 2 8 3 6 4.

Example 2

Input

4
-5 10 0 7

Output

-5 10 0 7

Explanation: Initial heap: {-5,0,7,10}. extractMin() → -5, heap {0,7,10}. extractMax() → 10, heap {0,7}. extractMin() → 0, heap {7}. Only one element left, so final extractMin() → 7. Result: -5 10 0 7.

Example 3

Input

1
42

Output

42

Explanation: With a single element, the algorithm performs only one extractMin(), returning 42.

Constraints

  • 1 <= N <= 200000
  • All A[i] are distinct
  • -10^9 <= A[i] <= 10^9
  • The algorithm must run in O(N log N) time and O(N) additional memory

Optimal Approach & Strategy

Build a min‑max heap in O(N) time, then perform extractMin followed by extractMax repeatedly, each in O(log N) by percolating down through alternating min/max levels.

Brute Force Approach

Sort the array once and then repeatedly pop from the front for min and from the back for max, which costs O(N log N) preprocessing and O(1) per extraction but uses extra space and loses the dynamic heap property.

Verified Code Solutions

JavaScript Solution
Time: O(N log N) for the full extraction sequence (O(N) build + O(N log N) for N/2 pairs of extracts)
function solution(nums) {
   let minHeap = [], maxHeap = [];
   for (let i = 0; i < nums.length; i++) {
       for (let j = 0; j < nums[i].length; j++) {
           if (nums[i][j] % 2 === 0) {
               minHeap.push(nums[i][j]);
           } else {
               maxHeap.push(nums[i][j]);
           }
       }
   }
   minHeap.sort((a, b) => a - b);
   maxHeap.sort((a, b) => b - a);
   let minSum = 0, maxSum = 0;
   while (minHeap.length > 0) {
       minSum += minHeap.shift();
   }
   while (maxHeap.length > 0) {
       maxSum += maxHeap.shift();
   }
   return minSum + maxSum;
}

Asked in Top Tech Interviews

SwiggyMeta

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.