#3510
Minimum Pair Removal to Sort Array II
HardArrayHash TableLinked ListHeap (Priority Queue)SimulationDoubly-Linked ListOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can use a priority queue to efficiently find and merge the minimum adjacent pairs, reducing the number of operations needed to sort the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a priority queue to store pairs of adjacent elements along with their sums.
- 2Step 2: Continuously extract the minimum sum pair, merge them, and update the queue until the array is sorted.
- 3Step 3: Count the number of merge operations performed.
solution.py17 lines
1import heapq
2
3def min_operations(nums):
4 ops = 0
5 pq = []
6 for i in range(len(nums) - 1):
7 heapq.heappush(pq, (nums[i] + nums[i + 1], i))
8 while pq:
9 _, idx = heapq.heappop(pq)
10 nums[idx] += nums[idx + 1]
11 nums.pop(idx + 1)
12 ops += 1
13 if idx > 0:
14 heapq.heappush(pq, (nums[idx - 1] + nums[idx], idx - 1))
15 if idx < len(nums) - 1:
16 heapq.heappush(pq, (nums[idx] + nums[idx + 1], idx))
17 return opsℹ
Complexity note: Using a priority queue allows us to efficiently manage and retrieve the minimum pairs.
- 1Adjacent pairs can be merged to reduce the array size.
- 2Using a priority queue optimizes the search for minimum pairs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.