Minimum Equal Sum of Two Arrays After Replacing Zeros solution and explanation
9 more videos on this problem
Minimum Equal Sum of Two Arrays After Replacing Zeros | Made Easy | Leetcode 2918 | codestorywithMIKcodestorywithMIK · 19:32 · 6K views
Minimum Equal Sum of Two Arrays After Replacing Zeros | Leetcode 2918Techdose · 10:01 · 1K views
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros (Leetcode Medium)Programming Live with Larry · 6:50 · 832 views
Daily Leetcode #1866: May 10, 2025 - 2918. Minimum Equal Sum of Two Arrays After Replacing ZerosProgramming Live with Larry · 8:17 · 509 views
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros | Leetcode Daily - PythonLeetcode Daily · 10:20 · 272 views
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros | Arrays | Greedy | LeetcodeRapid Syntax · 10:16 · 246 views
Minimum Equal Sum of Two Arrays After Replacing Zeros - Leetcode 2918 - PythonTim Huang · 5:08 · 185 views
Leetcode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros (simulation)LetsCode · 10:53 · 151 views
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros | Greedy | Python | LeetcodeBilaal Codes · 15:59 · 113 views
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros | Solving UNCUT 🔥 10-05-25LeetCode Daily LIVE · 13:46 · 45 views
The 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.
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 <= 1050 <= nums1[i], nums2[i] <= 106
Approach overview
Problem Overview: You get two integer arrays where some elements are 0. Each zero can be replaced with any positive integer. The goal is to choose replacements so both arrays end up with the same total sum, while keeping that common sum as small as possible.
Approach 1: Greedy Replacement Approach (O(n) time, O(1) space)
Scan both arrays once and compute two values for each: the current sum of non‑zero elements and the number of zeros. The smallest value a zero can contribute is 1, so the minimum possible sum for each array becomes sum + zeroCount. The smallest equal sum you can achieve must be at least the larger of these two minimum sums. If one array has no zeros and its fixed sum is smaller than the other array's minimum achievable sum, equality is impossible. Otherwise, the target sum is simply max(minSum1, minSum2). You can always distribute the extra value across zeros in the array with flexibility. This works because increasing any zero replacement only increases the total, so a greedy "minimum first" strategy guarantees the smallest feasible equal sum. Time complexity is O(n) for iterating through both arrays, and space complexity is O(1) since only counters and sums are stored. The logic relies on simple arithmetic and sequential scans over the array.
Approach 2: Dynamic Programming Approach (O(n * S) time, O(S) space)
A more theoretical approach models the problem as constructing reachable sums after replacing zeros. For each array, treat every zero as a variable that can contribute any positive value and compute reachable totals up to a reasonable bound using dynamic programming. After generating possible sums for both arrays, the smallest common value becomes the answer. While correct, this approach is far heavier than necessary because the range of possible sums can grow quickly as replacements increase. The DP state tracks which totals can be formed after processing elements, similar to subset‑sum style transitions. Time complexity grows with the sum bound (O(n * S)) and space is O(S), making it impractical for large inputs compared to the greedy observation.
Recommended for interviews: The greedy strategy is what interviewers expect. The key observation is that every zero must contribute at least 1, which immediately defines the minimum achievable sum of each array. From there, equality requires matching the larger minimum. Showing a brute reasoning first and then simplifying it into the greedy formula demonstrates strong problem‑solving ability and leads to a clean O(n) solution.
Approach 1: Greedy Replacement Approach
In this approach, after calculating the current sum of the non-zero elements, we'll need to replace zeros in a way that minimizes the absolute difference in sums of both arrays. The goal is to assign zero replacements such that the sums of both arrays converge to the smallest possible common value.
def min_equal_sum(nums1, nums2):
sum1, sum2 = 0, 0
zeros1, zeros2 = 0, 0
for num in nums1:
if num == 0:
zeros1 += 1
else:
sum1 += num
for num in nums2:
if num == 0:
zeros2 += 1
else:
sum2 += num
diff = abs(sum1 - sum2)
if zeros1 + zeros2 < diff:
return -1
return sum1 + sum2 + max(zeros1, zeros2)
print(min_equal_sum([3, 2, 0, 1, 0], [6, 5, 0]))class Solution {
public int minEqualSum(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0, zeros1 = 0, zeros2 = 0;
for (int n : nums1) {
if (n == 0) zeros1++;
else sum1 += n;
}
for (int n : nums2) {
if (n == 0) zeros2++;
else sum2 += n;
}
int diff = Math.abs(sum1 - sum2);
if (zeros1 + zeros2 < diff) return -1;
return (sum1 + sum2 + ((sum1 > sum2) ? zeros1 : zeros2));
}
public static void main(String[] args) {
Solution s = new Solution();
int[] nums1 = {3, 2, 0, 1, 0};
int[] nums2 = {6, 5, 0};
System.out.println(s.minEqualSum(nums1, nums2));
}
}#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int minEqualSum(vector<int>& nums1, vector<int>& nums2) {
int sum1 = 0, sum2 = 0, zeros1 = 0, zeros2 = 0;
for (int n : nums1) {
if (n == 0) zeros1++;
else sum1 += n;
}
for (int n : nums2) {
if (n == 0) zeros2++;
else sum2 += n;
}
int diff = abs(sum1 - sum2);
if (zeros1 + zeros2 < diff) return -1;
return (sum1 + sum2 + ((sum1 > sum2) ? zeros1 : zeros2));
}
int main() {
vector<int> nums1 = {3, 2, 0, 1, 0};
vector<int> nums2 = {6, 5, 0};
cout << minEqualSum(nums1, nums2) << endl;
return 0;
}function minEqualSum(nums1, nums2) {
let sum1 = 0,
sum2 = 0,
zeros1 = 0,
zeros2 = 0;
for (let num of nums1) {
if (num == 0) zeros1++;
else sum1 += num;
}
for (let num of nums2) {
if (num == 0) zeros2++;
else sum2 += num;
}
let diff = Math.abs(sum1 - sum2);
if (zeros1 + zeros2 < diff) return -1;
return sum1 + sum2 + Math.max(zeros1, zeros2);
}
console.log(minEqualSum([3, 2, 0, 1, 0], [6, 5, 0]));#include <stdio.h>
#include <stdlib.h>
int min_equal_sum(int* nums1, int size1, int* nums2, int size2) {
int sum1 = 0, sum2 = 0, zeros1 = 0, zeros2 = 0;
for (int i = 0; i < size1; i++) {
if (nums1[i] == 0) zeros1++;
else sum1 += nums1[i];
}
for (int i = 0; i < size2; i++) {
if (nums2[i] == 0) zeros2++;
else sum2 += nums2[i];
}
int diff = abs(sum1 - sum2);
if (zeros1 + zeros2 < diff) return -1;
return (sum1 + sum2 + ((sum1 > sum2) ? zeros1 : zeros2));
}
int main() {
int nums1[] = {3, 2, 0, 1, 0};
int nums2[] = {6, 5, 0};
int result = min_equal_sum(nums1, 5, nums2, 3);
printf("%d\n", result);
return 0;
}using System;
class Solution {
public int minEqualSum(int[] nums1, int[] nums2) {
int sum1 = 0, sum2 = 0, zeros1 = 0, zeros2 = 0;
foreach (int n in nums1) {
if (n == 0) zeros1++;
else sum1 += n;
}
foreach (int n in nums2) {
if (n == 0) zeros2++;
else sum2 += n;
}
int diff = Math.Abs(sum1 - sum2);
if (zeros1 + zeros2 < diff) return -1;
return (sum1 + sum2 + ((sum1 > sum2) ? zeros1 : zeros2));
}
static void Main() {
Solution s = new Solution();
int[] nums1 = {3, 2, 0, 1, 0};
int[] nums2 = {6, 5, 0};
Console.WriteLine(s.minEqualSum(nums1, nums2));
}
}The Python solution is straightforward, iterating through each list to count zeros and calculate their sums, then determining if it's possible to achieve equal sums.
Time Complexity: O(N + M) where N and M are the lengths of the input arrays. Space Complexity: O(1).
Approach 2: Dynamic Programming Approach
Another approach could involve dynamic programming where you maintain differences between sums while iteratively replacing zeros. However, this approach might not be efficient for larger inputs, given the freedom of allocating any positive integer. This theoretical method would track potential sums in a DP table.
# An illustrative Python concept would involve significant accounting for DP conditions.
# Commented here to reflect strategic limitations.
# Potential implementations outstrip the feasible given the exigencies of constraints and impact on time/space limits.// Java also faces a similar challenge: efficient tracking and dynamic state management is demanding and complex.
/* The constraints suggest pursuit in practicality lies in other approaches due to scalability issues in DP efforts for such scale limits. */// This comment placeholder suits for C++ as a similar evaluation of complexities with possibilities beyond practical efforts.// JavaScript approaches comparative challenges given expansive DP states.
/* Using JavaScript flexibility extends potential time concerns beyond practical solution implementation amid input-scale considerations. */// A Dynamic programming approach might involve tracking potential sums in a DP-like fashion.
/* Implementing it in C efficiently requires a careful strategy to adjust minimal sum changes and balance different possibilities, which involves significant complexity and is impractical for maximum constraints. */// In C# such state management lands this approach cumbersome.
// Implementing as a DP strategy involves intensive memory and time management.
// Similar practical unfeasibility under the constraints provided.Despite Python's flexibility, overcoming inherent tracking complexity issues is tedious, especially for very large input sizes.
Theoretical Time Complexity: O(X*Y), Space: O(X*Y) potentially but less practical.
Approach 3: Case Analysis
We consider the case where we treat all 0s in the array as 1s, and calculate the sum of the two arrays separately, denoted as s_1 and s_2. Without loss of generality, we assume that s_1 \le s_2.
- If
s_1 = s_2, then the answer iss_1. - If
s_1 \lt s_2, then there must exist a0innums1to make the sum of the two arrays equal. In this case, the answer iss_2. Otherwise, it means that it is impossible to make the sum of the two arrays equal, and we return-1.
The time complexity is O(n + m), where n and m are the lengths of the arrays nums1 and nums2, respectively. The space complexity is O(1).
function minSum(nums1: number[], nums2: number[]): number {
let [s1, s2] = [0, 0];
let hasZero = false;
for (const x of nums1) {
if (x === 0) {
hasZero = true;
}
s1 += Math.max(x, 1);
}
for (const x of nums2) {
s2 += Math.max(x, 1);
}
if (s1 > s2) {
return minSum(nums2, nums1);
}
if (s1 === s2) {
return s1;
}
return hasZero ? s2 : -1;
}func minSum(nums1 []int, nums2 []int) int64 {
s1, s2 := 0, 0
hasZero := false
for _, x := range nums1 {
if x == 0 {
hasZero = true
}
s1 += max(x, 1)
}
for _, x := range nums2 {
s2 += max(x, 1)
}
if s1 > s2 {
return minSum(nums2, nums1)
}
if s1 == s2 {
return int64(s1)
}
if hasZero {
return int64(s2)
}
return -1
}Complexity comparison
| Approach | Complexity |
|---|---|
| Greedy Replacement Approach | Time Complexity: O(N + M) where N and M are the lengths of the input arrays. Space Complexity: O(1). |
| Dynamic Programming Approach | Theoretical Time Complexity: O(X*Y), Space: O(X*Y) potentially but less practical. |
| Case Analysis | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Replacement | O(n) | O(1) | Best general solution. Compute sums and zero counts to derive the minimum equal sum directly. |
| Dynamic Programming | O(n * S) | O(S) | Useful for conceptual exploration of reachable sums, but inefficient for large ranges. |
Frequently asked questions
Is Minimum Equal Sum of Two Arrays After Replacing Zeros easy or hard?
The problem is rated Medium because the implementation is simple but the insight is subtle. Many first attempts try simulation or dynamic programming, while the correct approach relies on recognizing the minimum contribution of each zero and applying a greedy calculation.
Minimum Equal Sum of Two Arrays After Replacing Zeros Python/Java solution
Most implementations follow the same greedy logic: compute sums, count zeros, calculate the minimum achievable sum for each array, and return the maximum of those values if feasible. The code is straightforward in Python, Java, C++, C#, and JavaScript because it only requires loops and arithmetic checks.
How to solve Minimum Equal Sum of Two Arrays After Replacing Zeros in O(n)?
Iterate through both arrays and compute two metrics: total sum of non‑zero elements and number of zeros. The smallest sum each array can reach is sum + zeroCount. If both arrays can increase using zeros, the answer is max(minSum1, minSum2). If one array has no zeros and its sum is smaller than the other array's minimum achievable sum, forming an equal sum is impossible.
What is the best approach for Minimum Equal Sum of Two Arrays After Replacing Zeros?
The greedy approach is the most efficient. Compute the sum of non‑zero elements and the count of zeros in each array. Since every zero must be at least 1, the minimum achievable sum for each array is sum + zeroCount. The smallest equal sum is the maximum of those two values, unless a fixed array without zeros prevents matching it.
Is Minimum Equal Sum of Two Arrays After Replacing Zeros asked at Google/Amazon/Meta?
Problems involving greedy adjustments and array sum constraints frequently appear in interviews at companies like Amazon, Google, and Meta. This problem tests the ability to reason about constraints and derive a mathematical greedy rule instead of simulating replacements.
What data structure is used in Minimum Equal Sum of Two Arrays After Replacing Zeros?
The solution mainly uses arrays and simple counters. No advanced data structures are required. You track sums and zero counts while iterating through each array once.
What is the time complexity of Minimum Equal Sum of Two Arrays After Replacing Zeros?
The optimal greedy solution runs in O(n) time and O(1) extra space. You only scan both arrays once to calculate their sums and the number of zeros. All decisions are then derived from simple arithmetic comparisons.
