Minimum Equal Sum of Two Arrays After Replacing Zeros Problem
#2918
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2918.
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.
Example 1:
Input: nums1 = [3,2,0,1,0], nums2 = [6,5,0]
Output: 12
Explanation: We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
Example 2:
Input: nums1 = [2,0,2,0], nums2 = [1,4]
Output: -1
Explanation: It is impossible to make the sum of both arrays equal.
Constraints:
1 <= nums1.length, nums2.length <= 10^50 <= nums1[i], nums2[i] <= 10^6
Solution
Approach: Case Analysis
Every 0 must become at least 1, so first replace each 0 by 1 and compute the two sums s1 and s2. Assume s1 <= s2 (otherwise swap the arrays).
- If
s1 == s2, the answer iss1. - If
s1 < s2, the smaller array has to grow tos2. That is possible only ifnums1contains a0(a0can take any value), and then the answer iss2. With no0innums1its sum is fixed, so return-1.
Complexity: O(n + m) time and O(1) extra space, where n and m are the lengths of the arrays.
class Solution:
def minSum(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1) + nums1.count(0)
s2 = sum(nums2) + nums2.count(0)
if s1 > s2:
return self.minSum(nums2, nums1)
if s1 == s2:
return s1
return -1 if nums1.count(0) == 0 else s2