Widest Pair of Indices With Equal Range Sum - Problem

Given two binary arrays nums1 and nums2 of equal length, find the widest pair of indices (i, j) where i โ‰ค j such that the subarray sums are equal.

More formally, you need to find indices i and j such that:

  • nums1[i] + nums1[i+1] + ... + nums1[j] == nums2[i] + nums2[i+1] + ... + nums2[j]
  • The distance j - i + 1 is maximized

Example: If nums1 = [1,0,1] and nums2 = [0,1,1], then for indices (0,2): nums1[0:2] = 1+0+1 = 2 and nums2[0:2] = 0+1+1 = 2. The distance is 2-0+1 = 3.

Return the maximum distance of such a pair, or 0 if no valid pair exists.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [1,0,1], nums2 = [0,1,1]
โ€บ Output: 3
๐Ÿ’ก Note: For the entire array (i=0, j=2): sum of nums1[0:2] = 1+0+1 = 2, sum of nums2[0:2] = 0+1+1 = 2. Distance = 2-0+1 = 3.
example_2.py โ€” No Valid Pair
$ Input: nums1 = [1,1], nums2 = [0,0]
โ€บ Output: 0
๐Ÿ’ก Note: No subarray pair has equal sums. nums1 subarrays have sums [1,1,2] while nums2 subarrays have sums [0,0,0].
example_3.py โ€” Multiple Valid Pairs
$ Input: nums1 = [0,1,0,1], nums2 = [1,0,1,0]
โ€บ Output: 4
๐Ÿ’ก Note: The entire array works: sum of nums1 = 2, sum of nums2 = 2. Distance = 3-0+1 = 4. This is the maximum possible.

Visualization

Tap to expand
Problem TransformationEqual subarray sums โ†” Same prefix sum differencenums1: [1,0,1,0]nums2: [0,1,1,0]โ†’diff: [1,-1,0,0]prefix: [1,0,0,0]sum=0at i=-1sum=0at i=1Distance = 1-(-1) = 2๐ŸŽฏ Key Insight: Same prefix sum = Equal subarray sums!When prefix_sum[j] == prefix_sum[i-1], thensum1[i:j] == sum2[i:j] โœ“
Understanding the Visualization
1
Create difference array
For each position i, calculate diff[i] = nums1[i] - nums2[i]
2
Calculate prefix sums
Running sum of differences tells us the cumulative 'balance'
3
Use hash map
Store first occurrence of each prefix sum value
4
Find maximum distance
When prefix sum repeats, we found equal subarray sums
Key Takeaway
๐ŸŽฏ Key Insight: Transform the equal subarray sum problem into finding the widest span between identical prefix sum values in the difference array.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array with O(1) hash operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map can store up to n different prefix sums

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums1.length, nums2.length โ‰ค 105
  • nums1.length == nums2.length
  • nums1[i] and nums2[i] are either 0 or 1
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22
48.2K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen