Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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] <= 106Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[3,2,0,1,0] [6,5,0]
[2,0,2,0] [1,4]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
class Solution {
public long minSum(int[] nums1, int[] nums2) {
long s1 = 0, s2 = 0;
boolean hasZero = false;
for (int x : nums1) {
hasZero |= x == 0;
s1 += Math.max(x, 1);
}
for (int x : nums2) {
s2 += Math.max(x, 1);
}
if (s1 > s2) {
return minSum(nums2, nums1);
}
if (s1 == s2) {
return s1;
}
return hasZero ? s2 : -1;
}
}
// Accepted solution for LeetCode #2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
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
}
# Accepted solution for LeetCode #2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
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
// Accepted solution for LeetCode #2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
/**
* [2918] Minimum Equal Sum of Two Arrays After Replacing Zeros
*/
pub struct Solution {}
// submission codes start here
use std::cmp::Ordering;
impl Solution {
pub fn min_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i64 {
let mut nums1_sum: i64 = nums1.iter().map(|x| *x as i64).sum();
let mut nums2_sum: i64 = nums2.iter().map(|x| *x as i64).sum();
let nums1_zero_count = nums1.iter().filter(|x| **x == 0).count() as i64;
let nums2_zero_count = nums2.iter().filter(|x| **x == 0).count() as i64;
match (nums1_sum + nums1_zero_count).cmp(&(nums2_sum + nums2_zero_count)) {
Ordering::Less => {
if nums1_zero_count == 0 {
-1
} else {
nums2_sum + nums2_zero_count
}
}
Ordering::Greater => {
if nums2_zero_count == 0 {
-1
} else {
nums1_sum + nums1_zero_count
}
}
Ordering::Equal => nums1_sum + nums1_zero_count,
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2918() {
assert_eq!(12, Solution::min_sum(vec![3, 2, 0, 1, 0], vec![6, 5, 0]));
assert_eq!(-1, Solution::min_sum(vec![2, 0, 2, 0], vec![1, 4]));
}
}
// Accepted solution for LeetCode #2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
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;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.