Widest Pair of Indices With Equal Range Sum - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,0,1,1,0], nums2 = [0,1,1,1,0]
Output: 3
💡 Note: The widest pair is (2,4) where both arrays have sum 2 in range [2,4]. Distance = 4-2+1 = 3.
Example 2 — Equal Arrays
$ Input: nums1 = [1,1,0], nums2 = [1,1,0]
Output: 3
💡 Note: Arrays are identical, so entire range [0,2] has equal sums. Distance = 2-0+1 = 3.
Example 3 — No Valid Range
$ Input: nums1 = [1,0], nums2 = [0,1]
Output: 0
💡 Note: No range has equal sums: [0,0] has 1≠0, [1,1] has 0≠1, [0,1] has 1≠1.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • nums1.length == nums2.length
  • nums1[i], nums2[i] ∈ {0, 1}

Visualization

Tap to expand
Widest Pair of Indices With Equal Range Sum INPUT nums1: 1 0 1 1 0 0 1 2 3 4 nums2: 0 1 1 1 0 0 1 2 3 4 diff = nums1[i] - nums2[i]: 1 -1 0 0 0 Find widest subarray where sum of diff = 0 This means equal sums in both arrays! ALGORITHM (Hash) 1 Compute prefix sums prefixDiff[k] = sum(diff[0..k]) 2 Use HashMap Store first index of each prefix idx: -1 0 1 2 3 4 pre: 0 1 0 0 0 0 HashMap: sum 0 --> first at idx -1 sum 1 --> first at idx 0 3 Find repeated prefix Same prefix = zero sum subarray 4 Track max width At idx 1: prefix=0, first at -1 Width = 1 - (-1) = 2 Max found: idx 2,3,4 width=3 FINAL RESULT Widest pair: (i=2, j=4) nums1: 1 0 1 1 0 nums2: 0 1 1 1 0 indices 2 to 4 Verification: nums1[2:4] = 1+1+0 = 2 nums2[2:4] = 1+1+0 = 2 OUTPUT 3 Distance = j - i + 1 = 3 Key Insight: Transform the problem: If sum(nums1[i..j]) == sum(nums2[i..j]), then sum(diff[i..j]) == 0 where diff = nums1 - nums2. Use prefix sums with a HashMap: when the same prefix sum appears at indices a and b, the subarray (a+1, b) has sum zero. Store only the FIRST occurrence of each prefix sum to maximize width. Time: O(n), Space: O(n). TutorialsPoint - Widest Pair of Indices With Equal Range Sum | Hash Approach
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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