#2009
Minimum Number of Operations to Make Array Continuous
HardArrayHash TableBinary SearchSliding WindowHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses sorting and a sliding window approach to efficiently find the minimum number of operations needed. By focusing on the range of unique elements, we can minimize replacements.
⚙️
Algorithm
3 steps- 1Step 1: Sort the input array to arrange the numbers in increasing order.
- 2Step 2: Use a sliding window to find the longest continuous segment of unique numbers that can fit the criteria.
- 3Step 3: Calculate the number of operations needed as the difference between the total length and the length of the longest valid segment.
solution.py13 lines
1# Full working Python code
2
3def min_operations(nums):
4 nums = sorted(set(nums)) # Remove duplicates and sort
5 n = len(nums)
6 left = 0
7 min_operations = float('inf')
8 for right in range(n):
9 while nums[right] - nums[left] >= n:
10 left += 1
11 min_operations = min(min_operations, n - (right - left + 1))
12 return min_operations
13ℹ
Complexity note: The sorting step takes O(n log n), and the sliding window runs in O(n), making this approach efficient for large inputs.
- 1Sorting the array helps in easily identifying the range of unique numbers.
- 2Using a sliding window allows us to efficiently find the longest valid segment without unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.