Skip to main content
Back to problems
#3810
Medium Algorithms

Minimum operations to reach target array

Array Hash Table Greedy
63.4% acceptance
Mar 16, 2026
57
21
You are given two integer arrays nums and target, each of length n. Operation: Choose value x, find all maximal contiguous segments of x in nums, replace each segment with corresponding target values simultaneously. Return the minimum number of operations to make nums equal to target.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>, target: Vec<i32>) -> i32 {
    // The answer is the number of distinct values among positions where nums[i] != target[i].
    // When we choose x, ALL maximal contiguous segments of x get replaced simultaneously.
    // After replacement, those positions have their target values.
    // Positions where nums[i] == target[i] are unaffected (replacing with same value).
    use std::collections::HashSet;
    let mut vals = HashSet::new();
    for i in 0..nums.len() {
      if nums[i] != target[i] {
        vals.insert(nums[i]);
      }
    }
    vals.len() as i32
  }
}