581. Choose Numbers From Two Arrays in Range

Given two 0-indexed integer arrays arr1 and arr2, both of length n.

A range [l, r] (where 0 ≤ l ≤ r < n) is considered balanced if:

  • For every i in [l, r], you select either arr1[i] or arr2[i].
  • The sum of chosen elements from arr1 equals the sum of chosen elements from arr2. (If no elements are chosen from an array, the sum is considered 0.)

Two balanced ranges [l1, r1] and [l2, r2] are different if at least one of the following conditions holds:

  • l1 ≠ l2
  • r1 ≠ r2
  • For at least one index i, the selection differs between the two ranges (i.e., arr1[i] was chosen in one range and arr2[i] in the other).

Return the total number of distinct balanced ranges. Since the answer may be large, return it modulo 109 + 7.

Example 1:

Input: arr1 = [2,3,7], arr2 = [5,6,4]

Output: 3

Explanation:

The three balanced ranges are:

[0, 1] → Select arr2[0], arr1[1]: 3 = 3

[0, 2] → Select arr1[0], arr2[1], arr1[2]: 2 + 7 = 5 + 4

[0, 2] → Select arr1[0], arr1[1], arr2[2]: 2 + 3 = 5

Since different selections make them unique, they are counted separately.

Example 2:

Input: arr1 = [1,0], arr2 = [0,1]

Output: 4

Explanation:

The four balanced ranges are:

[0, 0] → Pick arr1[0]: 1 = 1

[1, 1] → Pick arr2[1]: 0 = 0

[0, 1] → Pick arr1[0], arr2[1]: 1 = 1

[0, 1] → Pick arr2[0], arr1[1]: 0 = 0

Now Your Turn!

Pick the correct output for the given input

Input: arr1 = [3,2,5], arr2 = [4,3,2]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n == arr1.length == arr2.length
  • 1 ≤ n ≤ 100
  • 0 ≤ arr1[i], arr2[i] ≤ 100

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int countSubranges(vector<int>& nums1, vector<int>& nums2) {
}
};
 
Test Case

Input:

Arr1
Arr2