Minimum Operations to Make Array Equal II - Problem
Transform One Array into Another
You're given two integer arrays
Each operation allows you to:
• Choose any two indices
• Add
• Subtract
This is like redistributing value between array elements in chunks of size
Challenge: Return the minimum number of operations needed, or
You're given two integer arrays
nums1 and nums2 of equal length n, and an integer k. Your goal is to make nums1 exactly equal to nums2 using the minimum number of special operations.Each operation allows you to:
• Choose any two indices
i and j• Add
k to nums1[i]• Subtract
k from nums1[j]This is like redistributing value between array elements in chunks of size
k. The arrays are considered equal when nums1[i] == nums2[i] for all valid indices.Challenge: Return the minimum number of operations needed, or
-1 if it's impossible to make them equal. Input & Output
example_1.py — Basic Operation
$
Input:
nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3
›
Output:
2
💡 Note:
We need 2 operations: First operation: add 3 to index 2, subtract 3 from index 0 → [1,3,4,4]. Second operation: add 3 to index 2, subtract 3 from index 3 → [1,3,7,1]. The differences are [-3,0,+6,-3], and we need to transfer the +6 surplus, requiring 6/3 = 2 operations.
example_2.py — Already Equal
$
Input:
nums1 = [3,8,5,2], nums2 = [3,8,5,2], k = 1
›
Output:
0
💡 Note:
The arrays are already equal, so no operations are needed.
example_3.py — Impossible Case
$
Input:
nums1 = [1,0,1,0], nums2 = [0,1,0,1], k = 2
›
Output:
-1
💡 Note:
Differences are [-1,+1,-1,+1]. Since -1 and +1 are not divisible by k=2, transformation is impossible.
Constraints
- n == nums1.length == nums2.length
- 1 ≤ n ≤ 105
- 0 ≤ nums1[i], nums2[i] ≤ 109
- 0 ≤ k ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Needs
Determine how much each position needs to gain or lose
2
Check Feasibility
Verify all differences are multiples of k and sum to zero
3
Count Operations
Sum up all positive differences (surplus) and divide by k
Key Takeaway
🎯 Key Insight: We only need to count positive differences (surplus elements) since each operation transfers from surplus to deficit, and the total operations equal sum of surpluses divided by k.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code