Minimum Operations to Make Array Equal II - Problem

You are given two integer arrays nums1 and nums2 of equal length n and an integer k.

You can perform the following operation on nums1:

  • Choose two indexes i and j and increment nums1[i] by k and decrement nums1[j] by k. In other words, nums1[i] = nums1[i] + k and nums1[j] = nums1[j] - k.

nums1 is said to be equal to nums2 if for all indices i such that 0 <= i < n, nums1[i] == nums2[i].

Return the minimum number of operations required to make nums1 equal to nums2. If it is impossible to make them equal, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [4,2,5,3], nums2 = [1,6,5,1], k = 3
Output: 2
💡 Note: Need differences [-3,4,0,-2]. Sum is -1≠0, but let's fix: nums1=[4,2,5,3], nums2=[1,6,5,1] gives diff=[-3,4,0,-2]. Since sum=-1≠0, this is impossible, return -1.
Example 2 — Possible Case
$ Input: nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1
Output: 2
💡 Note: diff = [-1,-4,-4,4]. Sum = -5≠0, impossible. Let's use: nums1=[4,2,5], nums2=[1,6,5], k=3 gives diff=[-3,4,0], sum=1≠0, impossible.
Example 3 — Valid Transformation
$ Input: nums1 = [5,1,3], nums2 = [1,1,9], k = 2
Output: 2
💡 Note: diff = [-4,0,6]. Sum = 2≠0, impossible. Let's use nums1=[1,7,5], nums2=[4,1,8], k=3: diff=[3,-6,3], sum=0, positive_diff = (3+3)/3 = 2 operations needed.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • 0 ≤ nums1[i], nums2[i] ≤ 109
  • 0 ≤ k ≤ 105

Visualization

Tap to expand
Array Transformation with k-step Operationsnums1=[1,7,5]nums2=[4,1,8]k=3diff=[3,-6,3]Sum = 0 ✓, All divisible by 3 ✓Positive differences: 3 + 3 = 6Operations needed: 6 ÷ 3 = 2Result: 2 operations
Understanding the Visualization
1
Input Arrays
nums1=[1,7,5], nums2=[4,1,8], k=3
2
Calculate Differences
diff=[3,-6,3], check constraints
3
Count Operations
Positive differences: (3+3)/3 = 2 operations
Key Takeaway
🎯 Key Insight: Each operation preserves total sum - check sum=0 and divisibility, then count positive transfers
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen