Minimum Number of Operations to Make Array Continuous - Problem
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.
Input & Output
Example 1 — Already Continuous
$
Input:
nums = [4,2,5,3]
›
Output:
0
💡 Note:
The array contains unique elements [2,3,4,5] and max-min = 5-2 = 3 = length-1. Already continuous, so 0 operations needed.
Example 2 — Need Replacements
$
Input:
nums = [1,2,3,5,6]
›
Output:
1
💡 Note:
We can keep 4 elements in range [2,5]: [2,3,5] plus one replacement. Or keep [1,2,3] plus two replacements. Best is 1 replacement.
Example 3 — Many Duplicates
$
Input:
nums = [1,10,100,1000]
›
Output:
3
💡 Note:
Only 1 element can be kept in any continuous range of length 4. Need to replace 3 elements.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [4,2,5,3] with length 4, need max-min = 3
2
Check Conditions
All unique? Yes. Range = 5-2 = 3 = length-1? Yes
3
Result
Already continuous, 0 operations needed
Key Takeaway
🎯 Key Insight: Keep maximum existing unique elements within any valid continuous range of length n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code