#2918
Minimum Equal Sum of Two Arrays After Replacing Zeros
MediumArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that we can replace zeros with the smallest possible integers (1) to balance the sums of the two arrays. By calculating the difference in sums and adjusting the zeros accordingly, we can find the minimum equal sum efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the current sums of both arrays, ignoring zeros.
- 2Step 2: Count the number of zeros in both arrays.
- 3Step 3: Determine the minimum sum that can be achieved by replacing zeros with 1s.
- 4Step 4: Check if the difference between the two sums can be compensated by the zeros available in the smaller sum array.
solution.py19 lines
1# Full working Python code
2
3def minEqualSum(nums1, nums2):
4 sum1 = sum(x for x in nums1 if x > 0)
5 sum2 = sum(x for x in nums2 if x > 0)
6 zeros1 = nums1.count(0)
7 zeros2 = nums2.count(0)
8
9 min_sum = sum1 + sum2 + zeros1 + zeros2
10
11 if sum1 < sum2:
12 if (sum2 - sum1) > zeros1:
13 return -1
14 else:
15 if (sum1 - sum2) > zeros2:
16 return -1
17
18 return min_sum
19ℹ
Complexity note: This complexity is linear because we only traverse each array once to compute sums and counts, making it efficient for large inputs.
- 1Replacing zeros with 1s is the minimum contribution to balance the sums.
- 2The array with the smaller sum must have enough zeros to cover the difference.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.