2009. Minimum Number of Operations to Make Array Continuous
UnknownView on LeetCode
Time: O(n log n)
Space: O(n)
Problem Overview
Minimum Number of Operations to Make Array Continuous (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Binary Search pattern in coding interviews. Sort + deduplicate; sliding window of size n; minimize elements outside window to replace.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sort + deduplicate; sliding window of size n; minimize elements outside window to replace.
Related patterns: Array, Binary Search, Sliding Window
2009.cs
C#
// Approach: Sort + deduplicate; sliding window of size n; minimize elements outside window to replace.
// Time: O(n log n) Space: O(n)
public class Solution
{
public int MinOperations(int[] nums)
{
int n = nums.Length;
int ans = n;
Array.Sort(nums);
nums = nums.Distinct().ToArray();
for (int i = 0; i < nums.Length; ++i)
{
int start = nums[i];
int end = start + n - 1;
int index = FirstGreater(nums, end);
int uniqueLength = index - i;
ans = Math.Min(ans, n - uniqueLength);
}
return ans;
}
private int FirstGreater(int[] A, int target)
{
int i = Array.BinarySearch(A, target + 1);
return i < 0 ? ~i : i;
}
}Was this solution helpful?
Related Problems
- 2106. Maximum Fruits Harvested After at Most K Steps(Unknown)
- 2271. Maximum White Tiles Covered by a Carpet(Unknown)
- 2302. Count Subarrays With Score Less Than K(Hard)
- 3013. Divide an Array Into Subarrays With Minimum Cost II(Unknown)
- 3346. Maximum Frequency of an Element After Performing Operations I(Medium)
- 3347. Maximum Frequency of an Element After Performing Operations II(Unknown)