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.
A continuous array spans \(n\) distinct values, so duplicates must change. With \(n \le 10^5\) we cannot try every target range. After sorting unique values, a valid window is a stretch whose max–min is at most \(n-1\).
For left endpoint \(nums[i]\), the right cannot exceed \(nums[i]+n-1\). Binary search finds the first overflow \(j\); we keep \(j-i\) numbers and perform \(n-(j-i)\) operations.
Sorting dominates; each query is \(O(\log n)\).
First, we sort the array and remove duplicates.
Then, we traverse the array, enumerating the current element \(nums[i]\) as the minimum value of the consecutive array. We use binary search to find the first position \(j\) that is greater than \(nums[i] + n - 1\). Then, \(j-i\) is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., \(ans = \min(ans, n - (j - i))\).
Finally, we return \(ans\).
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Here, \(n\) is the length of the array.
Solution 2: Sorting + Deduplication + Two Pointers
Thinking
Solution 1 binary-searches the right end each time. As \(i\) moves right, \(j\) is monotone, so binary search is unnecessary.
A two-pointer scan advances \(j\) once, dropping the extra \(\log n\) factor.
Similar to Solution 1, we first sort the array and remove duplicates.
Then, we traverse the array, enumerating the current element \(nums[i]\) as the minimum value of the consecutive array. We use two pointers to find the first position \(j\) that is greater than \(nums[i] + n - 1\). Then, \(j-i\) is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., \(ans = \min(ans, n - (j - i))\).
Finally, we return \(ans\).
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Here, \(n\) is the length of the array.