Minimum Equal Sum of Two Arrays After Replacing Zeros - Problem
Minimum Equal Sum of Two Arrays After Replacing Zeros

You are given two arrays nums1 and nums2 consisting of positive integers and zeros. Your task is to replace all zeros in both arrays with strictly positive integers (1, 2, 3, ...) such that the sum of elements in both arrays becomes equal.

The challenge is to find the minimum possible equal sum that can be achieved, or return -1 if it's impossible to make the sums equal.

Key Points:
  • Zeros must be replaced with positive integers (โ‰ฅ 1)
  • Non-zero elements cannot be changed
  • Both arrays must have the same final sum
  • We want the minimum possible equal sum

Example: If nums1 = [3, 2, 0, 1, 0] and nums2 = [6, 5, 0], we can replace zeros optimally to make both sums equal to 13.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [3, 2, 0, 1, 0], nums2 = [6, 5, 0]
โ€บ Output: 12
๐Ÿ’ก Note: Array 1: non-zero sum = 6, zeros = 2, min sum = 8. Array 2: non-zero sum = 11, zeros = 1, min sum = 12. Since max(8,12) = 12, we can make both equal 12: [3,2,1,1,5] and [6,5,1].
example_2.py โ€” Impossible Case
$ Input: nums1 = [1, 2], nums2 = [3, 4]
โ€บ Output: -1
๐Ÿ’ก Note: Array 1 has sum 3 with no zeros, Array 2 has sum 7 with no zeros. Since neither can be modified, they cannot be made equal.
example_3.py โ€” Edge Case
$ Input: nums1 = [0, 0], nums2 = [1, 1]
โ€บ Output: 2
๐Ÿ’ก Note: Array 1: min sum = 0 + 2 = 2. Array 2: sum = 2, no zeros. Both can equal 2: [1,1] and [1,1].

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 105
  • 0 โ‰ค nums1[i], nums2[i] โ‰ค 1000
  • At least one element in each array is positive

Visualization

Tap to expand
๐Ÿ›’ Shopping Cart Balance ProblemCart 1: [3,2,0,1,0]$3$2?$1?Fixed: $6, Mystery: 2 boxesCart 2: [6,5,0]$6$5?Fixed: $11, Mystery: 1 boxCart 1 Minimum$6 + 2ร—$1 = $8Can go higher!Cart 2 Minimum$11 + 1ร—$1 = $12Can go higher!Target: Max($8, $12) = $12Cart 1: [3,2,1,1,5] = $12Cart 2: [6,5,1] = $12
Understanding the Visualization
1
Count Fixed Items
Sum up all items with known prices in both carts
2
Count Mystery Boxes
Count how many mystery boxes (zeros) each cart has
3
Calculate Minimum Values
Minimum cart value = fixed items + (mystery boxes ร— $1)
4
Find Target Balance
The target is the higher of the two minimum values
5
Check Feasibility
If a cart has no mystery boxes but lower value, impossible to balance
Key Takeaway
๐ŸŽฏ Key Insight: The minimum equal sum is determined by the cart that needs the higher minimum value. The other cart can always adjust its mystery boxes to match this target.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
26.8K Views
Medium Frequency
~15 min Avg. Time
892 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