Minimum Equal Sum of Two Arrays After Replacing Zeros - Problem

You are given two arrays nums1 and nums2 consisting of positive integers. You have to replace all the 0's in both arrays with strictly positive integers such that the sum of elements of both arrays becomes equal.

Return the minimum equal sum you can obtain, or -1 if it is impossible.

Input & Output

Example 1 — Basic Case with Zeros
$ Input: nums1 = [3,2,0,1,0], nums2 = [6,5,0]
Output: 51
💡 Note: Replace zeros with 1: nums1 = [3,2,1,1,1] (sum=8), nums2 = [6,5,1] (sum=12). Since nums2 has higher sum and nums1 has more zeros, we can increase nums1's zeros to balance: nums1 = [3,2,1,1,5] gives sum=12. Answer is 12.
Example 2 — Impossible Case
$ Input: nums1 = [1,2], nums2 = [3,4]
Output: -1
💡 Note: No zeros in either array. nums1 sum = 3, nums2 sum = 7. Since we can't change any values, it's impossible to make them equal.
Example 3 — One Array Without Zeros
$ Input: nums1 = [1,1,1,1], nums2 = [0,0,0,0]
Output: 4
💡 Note: nums1 sum = 4 (no zeros), nums2 can be [1,1,1,1] with sum = 4. Both sums can be equal at 4.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • 0 ≤ nums1[i], nums2[i] ≤ 106

Visualization

Tap to expand
Minimum Equal Sum of Two Arrays After Replacing Zeros INPUT nums1 = [3,2,0,1,0] 3 2 0 1 0 Sum = 6, Zeros = 2 nums2 = [6,5,0] 6 5 0 Sum = 11, Zeros = 1 = Zero (to replace) = nums1 values = nums2 values ALGORITHM STEPS 1 Calculate Min Sums Replace each 0 with 1 min1 = 6+2 = 8 min2 = 11+1 = 12 2 Check Feasibility If no zeros and sums differ --> return -1 3 Find Target Sum target = max(min1, min2) target = max(8,12) = 12 4 Verify Achievability Check if both arrays can reach target sum nums1: 6 + [1,1] --> adjust to 12 nums2: 11 + [1] --> reaches 12 FINAL RESULT After Replacement: nums1 = [3,2,1,1,5] 3 2 1 1 5 Sum = 3+2+1+1+5 = 12 nums2 = [6,5,1] 6 5 1 Sum = 6+5+1 = 12 OUTPUT 12 Minimum Equal Sum Replaced Key Insight: The minimum sum is achieved when all zeros are replaced with 1 (smallest positive integer). The answer is max(sum1 + zeros1, sum2 + zeros2). If one array has no zeros but needs more sum, return -1. TutorialsPoint - Minimum Equal Sum of Two Arrays After Replacing Zeros | Greedy Approach
Asked in
Microsoft 15 Amazon 12
18.5K Views
Medium Frequency
~25 min Avg. Time
486 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