Minimum Number of Operations to Make Array Continuous - Problem
You are given an integer array nums and need to transform it into a continuous array with the minimum number of operations. In one operation, you can replace any element with any integer of your choice.

A continuous array must satisfy two critical conditions:
1. All elements are unique (no duplicates)
2. The range equals the length: max - min = nums.length - 1

For example, [4, 2, 5, 3] is continuous because all elements are unique and 5 - 2 = 3 = 4 - 1. However, [1, 2, 3, 5, 6] is not continuous because 6 - 1 = 5 โ‰  4.

Your goal is to find the minimum number of replacements needed to make the array continuous.

Input & Output

example_1.py โ€” Basic Continuous Array
$ Input: [4,2,5,3]
โ€บ Output: 0
๐Ÿ’ก Note: The array is already continuous. All elements are unique and the range 5-2=3 equals length-1=3. No operations needed.
example_2.py โ€” Array with Gaps
$ Input: [1,2,3,5,6]
โ€บ Output: 1
๐Ÿ’ก Note: We can keep 4 elements in a continuous range. For example, keep [2,3,5,6] and change one element to make [2,3,4,5] (change 6โ†’4) or [3,4,5,6] (change 2โ†’4). Only 1 operation needed.
example_3.py โ€” Array with Duplicates
$ Input: [1,10,100,1000]
โ€บ Output: 3
๐Ÿ’ก Note: The elements are too spread out. We can keep at most 1 element and need to replace the other 3 to form a continuous array like [1,2,3,4]. So 4-1=3 operations needed.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109

Visualization

Tap to expand
๐Ÿจ Hotel Room OptimizationCurrent guest rooms: [4, 2, 5, 3]Room 4Room 2Room 5Room 3Sorted rooms: [2, 3, 4, 5]Room 2Room 3Room 4Room 5Optimal consecutive range: [2, 3, 4, 5]Room 2 โœ“Room 3 โœ“Room 4 โœ“Room 5 โœ“Keep all 4 guests๐ŸŽฏ Result: 0 RelocationsAll guests already in consecutive rooms!
Understanding the Visualization
1
Survey Current Occupancy
Remove duplicate room assignments and sort: guests in rooms [2,3,4,5]
2
Find Best Consecutive Range
Use sliding window to find the best 4 consecutive rooms that keep most guests
3
Calculate Relocations
Rooms [2,3,4,5] keep all 4 guests, so 4-4=0 relocations needed
Key Takeaway
๐ŸŽฏ Key Insight: Use sliding window on sorted unique elements to find the maximum number of existing elements that can fit in any continuous range, minimizing the operations needed.
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
987 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