algoadvance

You are given a 0-indexed integer array nums. Determine whether there exist two subarrays of length 2 with equal sum. Note that subarrays must not overlap.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [4,2,4]
Output: true
Explanation: The subarrays (4,2) and (2,4) have the same sum of 6.

Example 2:

Input: nums = [1,2,3,4,5]
Output: false
Explanation: There are no two subarrays of length 2 that have the same sum.

Example 3:

Input: nums = [0,0,0]
Output: true
Explanation: The subarrays (0,0) and (0,0) have the same sum of 0.

Constraints:

Clarifying Questions

  1. Can the subarrays overlap?
    • No, the subarrays must not overlap.
  2. Do we need to find and return the subarrays or just determine if such subarrays exist?
    • We only need to determine if such subarrays exist and return True or False.
  3. What should we return if the array length is less than 2?
    • This constraint is not needed as per the problem constraints. The minimum length for nums is 2.

Strategy

  1. Iterate through the list nums to calculate the sums of all subarrays of length 2.
  2. Use a set to store these sums.
  3. As we compute the sum of each subarray of length 2, check if the sum already exists in the set.
  4. If it does, return True.
  5. If not, add the sum to the set.
  6. If we finish the iteration without finding any duplicate sums, return False.

This approach ensures we check for equal subarray sums efficiently, leveraging the properties of a set for O(1) average time complexity for lookups and insertions.

Code

def findSubarrays(nums):
    seen_sums = set()
    
    for i in range(len(nums) - 1):
        current_sum = nums[i] + nums[i + 1]
        if current_sum in seen_sums:
            return True
        seen_sums.add(current_sum)
    
    return False

# Test cases
print(findSubarrays([4, 2, 4]))    # Should return True
print(findSubarrays([1, 2, 3, 4, 5]))  # Should return False
print(findSubarrays([0, 0, 0]))   # Should return True

Time Complexity

This ensures the solution is efficient and scales well within the problem’s constraints.

Try our interview co-pilot at AlgoAdvance.com