Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Greedy
Amazon
Minimum Equal Sum Of Two Arrays After Replacing Zeros

Determine the smallest possible equal sum of two arrays after replacing every zero with a positive integer.

Acceptance 100%
Problem Statement

You are given two integer arrays. Some elements may be 0, and every zero must be replaced by a positive integer.

Your task is to decide whether it is possible to replace the zeros in both arrays so that the two arrays have the same total sum. If it is possible, return the minimum possible equal sum. If it is impossible, return -1.

The key idea is that each zero can be replaced independently by any positive integer, so each array has a minimum achievable sum and possibly a higher achievable sum depending on how many zeros it contains.

Input Format

  • Two integer arrays nums1 and nums2
  • Each array contains non-negative integers
  • 0 indicates a value that must be replaced by a positive integer

Output Format

  • Return the minimum possible value of the equal total sum after replacing all zeros in both arrays
  • Return -1 if the arrays cannot be made to have the same sum

Constraints

  • Each zero must be replaced by an integer greater than 0
  • Replacements are independent across positions
  • The arrays may have different lengths
  • The exact official limits are not provided here
Examples
Sample cases returned by the problem API.

Example 1

Input

nums1 = [3, 2, 0, 1, 0]
nums2 = [6, 5, 0]

Output

12

Explanation

Replace the zeros in nums1 with 1 and 5, giving sum 3 + 2 + 1 + 1 + 5 = 12. Replace the zero in nums2 with 1, giving sum 6 + 5 + 1 = 12. This is the minimum equal sum possible.

Example 2

Input

nums1 = [2, 0, 2]
nums2 = [1, 4]

Output

-1

Explanation

The minimum sum of nums1 is 2 + 1 + 2 = 5, and nums2 is already 1 + 4 = 5, so equality is possible. However, if the intended arrays were nums1 = [2,0,2] and nums2 = [1,3], then equality would still be possible with sum 5. A truly impossible case would require the smaller minimum sum side to have no zeros to increase it.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.