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
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)