Minimum Operations to Make the Array Alternating Problem
Description
LeetCode Problem 2170.
You are given a 0-indexed array nums consisting of n positive integers.
The array nums is called alternating if:
nums[i - 2] == nums[i], where2 <= i <= n - 1.nums[i - 1] != nums[i], where1 <= i <= n - 1.
In one operation, you can choose an index i and change nums[i] into any positive integer.
Return the minimum number of operations required to make the array alternating.
Example 1:
Input: nums = [3,1,3,2,4,3]
Output: 3
Explanation:
One way to make the array alternating is by converting it to [3,1,3,1,3,1].
The number of operations required in this case is 3.
It can be proven that it is not possible to make the array alternating in less than 3 operations.
Example 2:
Input: nums = [1,2,2,2,2]
Output: 2
Explanation:
One way to make the array alternating is by converting it to [1,2,1,2,1].
The number of operations required in this case is 2.
Note that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Count the values at even and odd positions
An alternating array has one value x at all even indices and another value y != x at all odd indices. Each operation changes one element, so the cost of a target pair (x, y) is the number of elements that do not already match it.
So for the even positions we want a value that is already as frequent as possible, and likewise for the odd positions. Count the values at even indices and at odd indices, and keep the most frequent and the second most frequent value of each side with their counts: (a0, a1) and (a2, a3) for even positions, (b0, b1) and (b2, b3) for odd positions.
- If the two most frequent values differ (
a0 != b0), use them: the answer isn - (a1 + b1). - Otherwise one side must settle for its runner-up, so take the better of the two options:
n - max(a1 + b3, a3 + b1).
A side with only one distinct value has a runner-up count of 0.
Complexity: time O(n), space O(n), where n is the length of nums.
from collections import Counter
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
def f(i: int) -> Tuple[int, int, int, int]:
k1 = k2 = 0
cnt = Counter(nums[i::2])
for k, v in cnt.items():
if cnt[k1] < v:
k2, k1 = k1, k
elif cnt[k2] < v:
k2 = k
return k1, cnt[k1], k2, cnt[k2]
a, b = f(0), f(1)
n = len(nums)
if a[0] != b[0]:
return n - (a[1] + b[1])
return n - max(a[1] + b[3], a[3] + b[1])