[LeetCode] Minimum Operations to Reach Target Array

3810. Minimum Operations to Reach Target Array

You are given two integer arrays nums and target, each of length n, where nums[i] is the current value at index i and target[i] is the desired value at index i.

You may perform the following operation any number of times (including zero):

  • Choose an integer value x
  • Find all maximal contiguous segments where nums[i] == x (a segment is maximal if it cannot be extended to the left or right while keeping all values equal to x)
  • For each such segment [l, r], update simultaneously:
    • nums[l] = target[l], nums[l + 1] = target[l + 1], ..., nums[r] = target[r]

Return the minimum number of operations required to make nums equal to target.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int minOperations(vector<int>& nums, vector<int>& target) {
unordered_set<int> us;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != target[i]) us.insert(nums[i]);
}
return us.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-operations-to-reach-target-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.