Skip to content

2009. Minimum Number of Operations to Make Array Continuous 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int minOperations(vector<int>& nums) {
    const int n = nums.size();
    int ans = n;

    sort(begin(nums), end(nums));
    nums.erase(unique(begin(nums), end(nums)), end(nums));

    for (int i = 0; i < nums.size(); ++i) {
      const int start = nums[i];
      const int end = start + n - 1;
      const int index = firstGreater(nums, end);
      const int uniqueLength = index - i;
      ans = min(ans, n - uniqueLength);
    }

    return ans;
  }

 private:
  int firstGreater(const vector<int>& nums, int target) {
    return upper_bound(begin(nums), end(nums), target) - begin(nums);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
  public int minOperations(int[] nums) {
    final int n = nums.length;
    int ans = n;

    Arrays.sort(nums);
    nums = Arrays.stream(nums).distinct().toArray();

    for (int i = 0; i < nums.length; ++i) {
      final int start = nums[i];
      final int end = start + n - 1;
      final int index = firstGreater(nums, end);
      final int uniqueLength = index - i;
      ans = Math.min(ans, n - uniqueLength);
    }

    return ans;
  }

  private int firstGreater(int[] nums, int target) {
    int l = 0;
    int r = nums.length;

    while (l < r) {
      final int m = (l + r) / 2;
      if (nums[m] > target)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minOperations(self, nums: List[int]) -> int:
    n = len(nums)
    ans = n
    nums = sorted(set(nums))

    for i, start in enumerate(nums):
      end = start + n - 1
      index = bisect_right(nums, end)
      uniqueLength = index - i
      ans = min(ans, n - uniqueLength)

    return ans