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 nums are unique.
  • The difference between the maximum element and the minimum element in nums equals nums.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
Make Array Continuous: [4,2,5,3]4253Original Array (length = 4)Requirements: 1) All unique ✓ 2) max - min = length - 12345Sorted: [2,3,4,5]Max = 5, Min = 2, Difference = 3 = 4-1 ✓Already continuous! Operations needed: 0
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
Asked in
Google 15 Microsoft 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen