Problem Description
Given two 0-indexed binary arrays, nums1 and nums2, find the widest pair of indices (i, j) (with i <= j) such that the sum of elements in nums1 between i and j equals the sum in nums2 over the same range. The "widest" pair is defined as the pair with the largest distance (j - i + 1). Return the distance of the widest pair, or 0 if no such pair exists.
Key Insights
- The problem can be reduced to finding a subarray where the difference between the prefix sums of nums1 and nums2 remains constant.
- Define a running difference: diff = (prefix sum of nums1) - (prefix sum of nums2).
- A subarray (i, j) has equal sums if diff[j] == diff[i-1] (or diff[j] == 0 for subarrays starting at index 0).
- Use a hash table (or dictionary) to record the earliest index each diff value is encountered.
- Compute the maximum width (j - i) by checking every index against its earliest occurrence.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(n)
Solution
The solution uses a prefix sum approach on both arrays combined into a running diff. We maintain a dictionary to store the first occurrence of each diff value. As we iterate over the indices, whenever we see that the same diff has been encountered before, it implies that the subarray between that previous index+1 and the current index has equal range sums. We then update the maximum distance accordingly. Note the trick of initializing the dictionary with diff 0 at index -1 to handle subarrays starting from index 0.