Minimum Adjacent Swaps to Partition Array Problem
Description
LeetCode Problem 3994.
You are given an integer array nums and two integers a and b such that a < b.
An array is called good if it can be split into three contiguous parts, in this order, such that:
- Every element in the first part is less than
a. - Every element in the second part is in the range
[a, b]inclusive. - Every element in the third part is greater than
b.
Any of the three parts may be empty.
In one adjacent swap, you may swap two neighboring elements of nums.
Return the minimum number of adjacent swaps required to make nums good. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,3,2,4,5,6], a = 3, b = 4
Output: 1
Explanation:
- Swap nums[1] and nums[2]. The array becomes [1, 2, 3, 4, 5, 6].
- This array is good because it can be split into [1, 2], [3, 4], and [5, 6].
Example 2:
Input: nums = [9,7,5,3], a = 4, b = 8
Output: 5
Explanation:
One sequence of optimal swaps is as follows:
- Swap nums[2] and nums[3]. The array becomes [9, 7, 3, 5].
- Swap nums[1] and nums[2]. The array becomes [9, 3, 7, 5].
- Swap nums[0] and nums[1]. The array becomes [3, 9, 7, 5].
- Swap nums[1] and nums[2]. The array becomes [3, 7, 9, 5].
- Swap nums[2] and nums[3]. The array becomes [3, 7, 5, 9].
- This array is good because it can be split into [3], [7, 5], and [9].
Example 3:
Input: nums = [3,7,5,9], a = 4, b = 8
Output: 0
Explanation:
The array is already good. No swaps are needed.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= a < b <= 10^9
Solution
Approach: Count the inversions of the three groups
Give every element a type: 0 if it is less than a, 1 if it lies in [a, b], and 2 if it is greater than b. The array is good exactly when the types are in non-decreasing order, and the order inside one type does not matter.
An adjacent swap of two equal types changes nothing, and an adjacent swap of two different types fixes at most one out-of-order pair. So the minimum number of swaps equals the number of pairs i < j with type[i] > type[j]. Scan the array once and keep a counter for each type: for the current element, add the number of earlier elements with a larger type. The count can reach about n^2 / 3, so it needs 64-bit integers before taking the result modulo 10^9 + 7.
Complexity: time O(n), space O(1).
class Solution:
def minAdjacentSwaps(self, nums: List[int], a: int, b: int) -> int:
mod = 10**9 + 7
cnt = [0, 0, 0]
inversions = 0
for x in nums:
t = 0 if x < a else (1 if x <= b else 2)
# every earlier element of a larger type must be swapped past x
for u in range(t + 1, 3):
inversions += cnt[u]
cnt[t] += 1
return inversions % mod