Skip to main content
Back to problems
#2009
Hard Algorithms

Minimum number of operations to make array continuous

Array Hash Table Binary Search Sliding Window
52.1% acceptance
Feb 25, 2026
1989
53
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: All elements in nums are unique. The difference between the maximum element and the minimum element in nums equals nums.length - 1. Return the minimum number of operations to make nums continuous.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut sorted = nums.clone();
    sorted.sort();
    sorted.dedup();
    let m = sorted.len();
    let mut best = 0;
    let mut r = 0;
    for l in 0..m {
      while r < m && sorted[r] < sorted[l] + n as i32 {
        r += 1;
      }
      best = best.max(r - l);
    }
    (n - best) as i32
  }
}