Problem Description
Given two integer arrays nums1 and nums2 of equal length and an integer k, you can perform operations on nums1. In each operation, you select two indices i and j and update nums1 by incrementing nums1[i] by k and decrementing nums1[j] by k. The goal is to determine the minimum number of operations needed to transform nums1 into nums2. If it is impossible, return -1.
Key Insights
- Each operation transfers a fixed unit (k) from one index to another while preserving the overall sum.
- The total change required (diff = nums2[i] - nums1[i]) for each element must be divisible by k if k > 0.
- When k is zero, no changes can be made, so the arrays must already be equal.
- Convert each difference into units by dividing by k. The sum of these units across all indices must be zero; otherwise, it is impossible to balance the adjustments.
- The minimum number of operations is equal to the total positive units needed (which equals the total negative units in absolute value).
Space and Time Complexity
Time Complexity: O(n) – One pass through the arrays to compute the differences and validate conditions. Space Complexity: O(1) – Uses a constant amount of additional space.
Solution
We start by checking whether k is zero; if so, we return 0 if nums1 already equals nums2 or -1 if not. For k > 0, calculate the difference diff = nums2[i] - nums1[i] for each index. If diff is not divisible by k for any element, return -1. Otherwise, convert the diff into units by diff / k and accumulate these units. If the sum of all units is not zero, the transformation is impossible. The answer is then the sum of all positive units, which represents the minimum number of k-unit transfers required to achieve the target array.