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
Minimum Operations to Make Array Continuous INPUT nums = [4, 2, 5, 3] 4 2 5 3 i=0 i=1 i=2 i=3 Continuous Array Needs: 1. All elements unique 2. max - min = n - 1 Current Array Stats: n = 4, max = 5, min = 2 max - min = 3 = n - 1 [OK] ALGORITHM STEPS 1 Sort + Remove Dups Sorted: [2, 3, 4, 5] 2 Sliding Window Find max elements in range [x, x + n - 1] 3 Check Each Window Window [2,5]: has 4 elems All fit! Count = 4 4 Calculate Operations ops = n - maxCount ops = 4 - 4 = 0 Sliding Window on Sorted: 2 3 4 5 FINAL RESULT Array is already continuous! 2 3 4 5 (Sorted view for clarity) Verification: All unique: [OK] 5 - 2 = 3 = 4 - 1: [OK] Continuous! OUTPUT 0 Key Insight: For a continuous array of length n, elements must span exactly n consecutive integers. Use sliding window on sorted unique elements: find max elements fitting in any window of size n. Operations needed = n - maxElementsInWindow. Time: O(n log n), Space: O(n) TutorialsPoint - Minimum Number of Operations to Make Array Continuous | Optimal Solution
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