Problem Description
You are given two arrays nums1 and nums2 consisting of positive integers and possibly zeros. You must replace all the zeros in both arrays with strictly positive integers so that after replacement, the sum of the elements in both arrays is equal. Return the minimum equal sum you can obtain after replacements, or -1 if it is impossible.
Key Insights
- The non-zero elements in each array are fixed; only the zeros can be replaced.
- Since each replacement must be a strictly positive integer, each zero contributes at least 1 to the sum.
- For an array, the minimum achievable sum is the sum of its non-zero elements plus the number of zeros.
- If an array has no zeros (i.e. is fixed), its sum cannot change.
- The valid target equal sum must be at least the maximum of the two arrays’ minimum possible sums.
- For any array without zeros, the target sum must equal its fixed sum; if not, it is impossible.
- When one array is fixed and the other has zeros, the fixed array’s sum must be at least the minimum possible sum for the other array.
Space and Time Complexity
Time Complexity: O(n + m) where n and m are the lengths of the two arrays (one pass each to compute sums and zero counts). Space Complexity: O(1) extra space (only a few variables are used for calculations).
Solution
We compute the base (non-zero) sum and count the zeros in each array. For an array with zeros, the minimum achievable sum is (base sum + count of zeros) because each zero must contribute at least 1. For an array with no zeros, the sum is fixed. Let:
- base1 and z1 be the non-zero sum and zero count for nums1,
- base2 and z2 for nums2. The minimum sums are:
- min1 = (z1 > 0 ? base1 + z1 : base1)
- min2 = (z2 > 0 ? base2 + z2 : base2) The candidate target sum is max(min1, min2), since each array can achieve any sum greater than or equal to its minimum by allocating additional value to its zeros. However, if one array is fixed (i.e. has zero count 0) then the target must equal its fixed sum. Therefore, if candidate does not equal the fixed sum for any array, the answer is impossible (return -1).