LeetCode 2395. Find Subarrays With Equal Sum Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2395. Find Subarrays With Equal Sum

Description

Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.

Return true if these subarrays exist, and false otherwise.

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 with elements [4,2] and [2,4] have the same sum of 6.

Example 2:

Input: nums = [1,2,3,4,5]
Output: false
Explanation: No two subarrays of size 2 have the same sum.

Example 3:

Input: nums = [0,0,0]
Output: true
Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. 
Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.

 

Constraints:

  • 2 <= nums.length <= 1000
  • -109 <= nums[i] <= 109

Solutions

Solution 1: Hash Table

We can traverse the array nums, and use a hash table vis to record the sum of every two adjacent elements in the array. If the sum of the current two elements has already appeared in the hash table, then return true. Otherwise, add the sum of the current two elements to the hash table.

If we finish traversing and haven't found two subarrays that meet the condition, return false.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the array nums.

PythonJavaC++GoTypeScriptRustC
class Solution: def findSubarrays(self, nums: List[int]) -> bool: vis = set() for a, b in pairwise(nums): if (x := a + b) in vis: return True vis.add(x) return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !