Minimum Number of Operations to Make Array Continuous Problem
Description
LeetCode Problem 2009.
You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
- All elements in
numsare unique. - The difference between the maximum element and the minimum element in
numsequalsnums.length - 1.
For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
Example 1:
Input: nums = [4,2,5,3]
Output: 0
Explanation: nums is already continuous.
Example 2:
Input: nums = [1,2,3,5,6]
Output: 1
Explanation: One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.
Example 3:
Input: nums = [1,10,100,1000]
Output: 3
Explanation: One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Sort, Deduplicate, Binary Search
An array is continuous when it holds n distinct values that form a run of consecutive integers. Each operation can change one element into anything, so the cost is the number of elements we must change: n minus the number of elements we keep. Duplicates must always be changed (only one copy of a value can stay), so work with the sorted distinct values.
Suppose the smallest kept value is nums[i]. The final array then covers [nums[i], nums[i] + n - 1], and we can keep every distinct value inside that window. Binary search for j, the first position whose value exceeds nums[i] + n - 1; the kept values are j - i, so the cost is n - (j - i). Try every i and take the minimum.
Complexity: O(n log n) time and O(n) space (or O(log n) if the array is deduplicated in place).
from bisect import bisect_right
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = n = len(nums)
nums = sorted(set(nums))
for i, v in enumerate(nums):
j = bisect_right(nums, v + n - 1)
ans = min(ans, n - (j - i))
return ans