Minimum Number of Operations to Make Array Continuous - Problem
You are given an integer array
A continuous array must satisfy two critical conditions:
1. All elements are unique (no duplicates)
2. The range equals the length:
For example,
Your goal is to find the minimum number of replacements needed to make the array continuous.
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 - 1For 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code