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:
2 <= nums.length <= 1000-10^9 <= nums[i] <= 10^9True or False.nums is 2.nums to calculate the sums of all subarrays of length 2.True.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.
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
nums. We iterate through the array once.seen_sums set.This ensures the solution is efficient and scales well within the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?