Minimum Pair Removal to Sort Array II Problem
#3510
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3510.
Given an array nums, you can perform the following operation any number of times:
- Select the adjacent pair with the minimum sum in
nums. If multiple such pairs exist, choose the leftmost one. - Replace the pair with their sum.
Return the minimum number of operations needed to make the array non-decreasing.
An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists).
Example 1:
Input: nums = [5,2,3,1]
Output: 2
Explanation:
- The pair (3,1) has the minimum sum of 4. After replacement, nums = [5,2,4].
- The pair (2,4) has the minimum sum of 6. After replacement, nums = [5,6].
The array nums became non-decreasing in two operations.
Example 2:
Input: nums = [1,2,2]
Output: 0
Explanation:
The array nums is already sorted.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Heap + Linked List
Simulate the operation, but make each step cheap.
- Keep the array as a doubly linked list (
prevandnextarrays), so merging two neighbours isO(1). - Keep a min-heap of
(pair sum, left index). Ties on the sum go to the smaller index, which is the leftmost pair. When a pair changes, push its new entry and skip outdated entries when they are popped (an entry is outdated if its left element was removed or the pair sum no longer matches). - Keep
inv, the number of adjacent pairs that are out of order. The array is non-decreasing exactly wheninv == 0.
Each step takes the cheapest pair (i, j), subtracts the pair (i, j) from inv if it was out of order, and re-checks the two neighbouring pairs (p, i) and (j, k) before and after i takes the new value a[i] + a[j]. Repeat until inv is zero and return the number of steps.
Complexity: time O(n log n), space O(n).
from heapq import heapify, heappop, heappush
class Solution:
def minimumPairRemoval(self, nums: List[int]) -> int:
n = len(nums)
a = nums[:]
nxt = list(range(1, n + 1)) # next alive index (n if none)
prv = list(range(-1, n - 1)) # previous alive index (-1 if none)
alive = [True] * n
inv = sum(1 for i in range(n - 1) if a[i] > a[i + 1]) # adjacent pairs that are out of order
h = [(a[i] + a[i + 1], i) for i in range(n - 1)] # (pair sum, left index)
heapify(h)
ans = 0
while inv:
s, i = heappop(h)
# skip entries that are out of date
if not alive[i] or nxt[i] >= n or a[i] + a[nxt[i]] != s:
continue
j = nxt[i]
ans += 1
if a[i] > a[j]:
inv -= 1
p, k = prv[i], nxt[j]
if p >= 0:
if a[p] > a[i]:
inv -= 1
if a[p] > s:
inv += 1
if k < n:
if a[j] > a[k]:
inv -= 1
if s > a[k]:
inv += 1
# merge j into i
a[i] = s
alive[j] = False
nxt[i] = k
if k < n:
prv[k] = i
if p >= 0:
heappush(h, (a[p] + s, p))
if k < n:
heappush(h, (s + a[k], i))
return ans