KatInterview

519. Widest Pair of Indices With Equal Range Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the widest pair of indices (i, j) such that the sum of elements in nums1 from i to j is equal to the sum of elements in nums2 from i to j. The width is defined as j - i + 1.

Solution

Widest Pair of Indices With Equal Range Sum in Python

class Solution:
    def widestPairOfIndices(self, nums1: List[int], nums2: List[int]) -> int:
        # The problem is equivalent to finding the longest subarray in a difference array
        # `diff[i] = nums1[i] - nums2[i]` that has a sum of 0.
        # This can be solved using prefix sums and a hash map.

        # Use a dictionary to store the first occurrence of a prefix sum difference.
        # Key: prefix_sum_diff, Value: index
        first_occurrence = {0: -1}
        
        max_len = 0
        current_sum_diff = 0
        
        for i in range(len(nums1)):
            # Calculate the difference at the current index and add to the running sum.
            current_sum_diff += nums1[i] - nums2[i]
            
            # If we have seen this sum difference before...
            if current_sum_diff in first_occurrence:
                # ...it means the subarray between the previous occurrence and now
                # has a sum difference of 0. The length of this subarray is i - first_occurrence[current_sum_diff].
                max_len = max(max_len, i - first_occurrence[current_sum_diff])
            else:
                # If this is the first time we see this sum difference, record its index.
                # We only record the first one because we want to maximize the length.
                first_occurrence[current_sum_diff] = i
                
        return max_len

Widest Pair of Indices With Equal Range Sum in Java

class Solution {
    public int widestPairOfIndices(int[] nums1, int[] nums2) {
        // The problem is equivalent to finding the longest subarray in a difference array
        // `diff[i] = nums1[i] - nums2[i]` that has a sum of 0.
        // This can be solved using prefix sums and a hash map.

        // Use a map to store the first occurrence of a prefix sum difference.
        // Key: prefix_sum_diff, Value: index
        Map<Integer, Integer> firstOccurrence = new HashMap<>();
        
        // Initialize for the case where a subarray starting from index 0 has a sum of 0.
        // A prefix sum of 0 at index i means the subarray from 0 to i has a sum of 0.
        // Its length is i - (-1) = i + 1.
        firstOccurrence.put(0, -1);
        
        int maxLen = 0;
        int currentSumDiff = 0;
        int n = nums1.length;
        
        for (int i = 0; i < n; i++) {
            // Calculate the difference at the current index and add to the running sum.
            currentSumDiff += nums1[i] - nums2[i];
            
            // If we have seen this sum difference before...
            if (firstOccurrence.containsKey(currentSumDiff)) {
                // ...it means the subarray between the previous occurrence and now
                // has a sum difference of 0. The length of this subarray is i - firstOccurrence.get(currentSumDiff).
                maxLen = Math.max(maxLen, i - firstOccurrence.get(currentSumDiff));
            } else {
                // If this is the first time we see this sum difference, record its index.
                // We only record the first one because we want to maximize the length.
                firstOccurrence.put(currentSumDiff, i);
            }
        }
        
        return maxLen;
    }
}

Widest Pair of Indices With Equal Range Sum in C++

class Solution {
public:
    int widestPairOfIndices(vector<int>& nums1, vector<int>& nums2) {
        // The problem is equivalent to finding the longest subarray in a difference array
        // `diff[i] = nums1[i] - nums2[i]` that has a sum of 0.
        // This can be solved using prefix sums and a hash map.

        // Use a map to store the first occurrence of a prefix sum difference.
        // Key: prefix_sum_diff, Value: index
        unordered_map<int, int> first_occurrence;
        
        // Initialize for the case where a subarray starting from index 0 has a sum of 0.
        // A prefix sum of 0 at index i means the subarray from 0 to i has a sum of 0.
        // Its length is i - (-1) = i + 1.
        first_occurrence[0] = -1;
        
        int max_len = 0;
        int current_sum_diff = 0;
        int n = nums1.size();
        
        for (int i = 0; i < n; ++i) {
            // Calculate the difference at the current index and add to the running sum.
            current_sum_diff += nums1[i] - nums2[i];
            
            // If we have seen this sum difference before...
            if (first_occurrence.count(current_sum_diff)) {
                // ...it means the subarray between the previous occurrence and now
                // has a sum difference of 0. The length of this subarray is i - first_occurrence[current_sum_diff].
                max_len = max(max_len, i - first_occurrence[current_sum_diff]);
            } else {
                // If this is the first time we see this sum difference, record its index.
                // We only record the first one because we want to maximize the length.
                first_occurrence[current_sum_diff] = i;
            }
        }
        
        return max_len;
    }
};

Widest Pair of Indices With Equal Range Sum in TypeScript

function widestPairOfIndices(nums1: number[], nums2: number[]): number {
    // The problem is equivalent to finding the longest subarray in a difference array
    // `diff[i] = nums1[i] - nums2[i]` that has a sum of 0.
    // This can be solved using prefix sums and a hash map.

    // Use a map to store the first occurrence of a prefix sum difference.
    // Key: prefix_sum_diff, Value: index
    const firstOccurrence = new Map<number, number>();
    
    // Initialize for the case where a subarray starting from index 0 has a sum of 0.
    // A prefix sum of 0 at index i means the subarray from 0 to i has a sum of 0.
    // Its length is i - (-1) = i + 1.
    firstOccurrence.set(0, -1);
    
    let maxLen = 0;
    let currentSumDiff = 0;
    const n = nums1.length;
    
    for (let i = 0; i < n; i++) {
        // Calculate the difference at the current index and add to the running sum.
        currentSumDiff += nums1[i] - nums2[i];
        
        // If we have seen this sum difference before...
        if (firstOccurrence.has(currentSumDiff)) {
            // ...it means the subarray between the previous occurrence and now
            // has a sum difference of 0. The length of this subarray is i - firstOccurrence.get(currentSumDiff)!.
            maxLen = Math.max(maxLen, i - firstOccurrence.get(currentSumDiff)!);
        } else {
            // If this is the first time we see this sum difference, record its index.
            // We only record the first one because we want to maximize the length.
            firstOccurrence.set(currentSumDiff, i);
        }
    }
    
    return maxLen;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.