Skip to content

2009. Minimum Number of Operations to Make Array Continuous 👍

  • Time: $O(\texttt{sort})$
  • 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;

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

    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>& A, int target) {
    return ranges::upper_bound(A, target) - A.begin();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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[] A, int target) {
    final int i = Arrays.binarySearch(A, target + 1);
    return i < 0 ? -i - 1 : i;
  }
}
 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