Widest Pair of Indices With Equal Range Sum Problem
Description
LeetCode Problem 1983.
You are given two 0-indexed binary arrays nums1 and nums2. Find the widest pair of indices (i, j) such that i <= j and nums1[i] + nums1[i+1] + ... + nums1[j] == nums2[i] + nums2[i+1] + ... + nums2[j].
The widest pair of indices is the pair with the largest distance between i and j. The distance between a pair of indices is defined as j - i + 1.
Return the distance of the widest pair of indices. If no pair of indices meets the conditions, return 0.
Example 1:
Input: nums1 = [1,1,0,1], nums2 = [0,1,1,0]
Output: 3
Explanation:
If i = 1 and j = 3:
nums1[1] + nums1[2] + nums1[3] = 1 + 0 + 1 = 2.
nums2[1] + nums2[2] + nums2[3] = 1 + 1 + 0 = 2.
The distance between i and j is j - i + 1 = 3 - 1 + 1 = 3.
Example 2:
Input: nums1 = [0,1], nums2 = [1,1]
Output: 1
Explanation:
If i = 1 and j = 1:
nums1[1] = 1.
nums2[1] = 1.
The distance between i and j is j - i + 1 = 1 - 1 + 1 = 1.
Example 3:
Input: nums1 = [0], nums2 = [1]
Output: 0
Explanation:
There are no pairs of indices that meet the requirements.
Constraints:
n == nums1.length == nums2.length1 <= n <= 10^5nums1[i]is either0or1.nums2[i]is either0or1.
Solution
Approach: Prefix Sum + Hash Table
The two ranges have equal sums exactly when the sum of nums1[k] - nums2[k] over the range is 0. So build the difference array and look for its longest subarray with sum 0.
Walk through the indices keeping the running sum s of the differences. A zero-sum subarray ends at i when the same running sum was seen before. Store in a hash table the first index where each running sum appeared (with 0 -> -1 for the empty prefix), and for each i update the answer with i - first[s].
Complexity: time O(n), space O(n).
class Solution:
def widestPairOfIndices(self, nums1: List[int], nums2: List[int]) -> int:
d = {0: -1}
ans = s = 0
for i, (a, b) in enumerate(zip(nums1, nums2)):
s += a - b
if s in d:
ans = max(ans, i - d[s])
else:
d[s] = i
return ans