Skip to main content
Back to problems
#3375
Easy Algorithms

Minimum operations to make array values equal to k

Array Hash Table
73.3% acceptance
Feb 24, 2026
406
531
You are given an integer array nums and an integer k. An integer h is called valid if all values in the array that are strictly greater than h are identical. For example, if nums = [10, 8, 10, 8], a valid integer is h = 9 because all nums[i] > 9 are equal to 10, but 5 is not a valid integer. You are allowed to perform the following operation on nums: Select an integer h that is valid for the current values in nums. For each index i where nums[i] > h, set nums[i] to h. Return the minimum number of operations required to make every element in nums equal to k. If it is impossible to make all elements equal to k, return -1.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
    // If any element < k, impossible
    if nums.iter().any(|&x| x < k) {
      return -1;
    }
    // Count distinct values > k  (each distinct level requires one operation)
    let mut set = std::collections::HashSet::new();
    for &x in &nums {
      if x > k {
        set.insert(x);
      }
    }
    set.len() as i32
  }
}