Find Subarrays With Equal Sum

The problem asks for determining whether there are two subarrays of length 2 with equal sum. To find the solution, we can iterate through the array, calculating the sum of every 2 elements, and keep track of the sums we’ve already seen. If we find a sum that we’ve already seen before, we return true. If we go through the entire array without finding two subarrays with the same sum, we return false.

Here’s a method to implement this logic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def findSubarrays(self, nums: List[int]) -> bool:
        seen_sums = set() # To keep track of the sums we've already seen

        # Iterate through the array, but stop 1 before the end, since we are looking at pairs
        for i in range(len(nums) - 1):
            current_sum = nums[i] + nums[i + 1]

            # If this sum has been seen before, return true
            if current_sum in seen_sums:
                return True
            
            # Otherwise, add the sum to our set of seen sums
            seen_sums.add(current_sum)

        # If no equal subarrays found, return false
        return False

Example

For the input nums = [4,2,4], the method would return true, since the subarrays [4,2] and [2,4] have the same sum of 6.