Skip to content

1983. Widest Pair of Indices With Equal Range Sum 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int widestPairOfIndices(vector<int>& nums1, vector<int>& nums2) {
    int ans = 0;
    int prefix = 0;
    unordered_map<int, int> prefixToIndex{{0, -1}};

    for (int i = 0; i < nums1.size(); ++i) {
      prefix += nums1[i] - nums2[i];
      if (const auto it = prefixToIndex.find(prefix);
          it != prefixToIndex.cend())
        ans = max(ans, i - it->second);
      else
        prefixToIndex[prefix] = i;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int widestPairOfIndices(int[] nums1, int[] nums2) {
    int ans = 0;
    int prefix = 0;
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < nums1.length; ++i) {
      prefix += nums1[i] - nums2[i];
      if (prefixToIndex.containsKey(prefix))
        ans = Math.max(ans, i - prefixToIndex.get(prefix));
      else
        prefixToIndex.put(prefix, i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def widestPairOfIndices(self, nums1: list[int], nums2: list[int]) -> int:
    ans = 0
    prefix = 0
    prefixToIndex = {0: -1}

    for i, (num1, num2) in enumerate(zip(nums1, nums2)):
      prefix += num1 - num2
      ans = max(ans, i - prefixToIndex.setdefault(prefix, i))

    return ans