Leetcode 2395. Find Subarrays With Equal Sum
You are given a 0-indexed integer array nums
. You need to find if there are at least two subarrays of length 2 with equal sum. Return true
if such subarrays exist and false
otherwise.
Input: nums = [4,2,4]
Output: true
Explanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.
Input: nums = [1,2,3,4,5]
Output: false
Explanation: No two subarrays of length 2 have the same sum.
nums
?
nums
can be between 1 and 1000.nums
be negative?
nums
can include negative numbers.nums
always have at least 2 elements?
true
.false
.import java.util.HashSet;
import java.util.Set;
public class SubarraysWithEqualSum {
public boolean findSubarraysWithEqualSum(int[] nums) {
Set<Integer> sums = new HashSet<>();
for (int i = 0; i < nums.length - 1; i++) {
int sum = nums[i] + nums[i + 1];
if (!sums.add(sum)) {
// sums.add(sum) returns false if the sum already exists in the set
return true;
}
}
return false;
}
public static void main(String[] args) {
SubarraysWithEqualSum solution = new SubarraysWithEqualSum();
int[] nums1 = {4, 2, 4};
int[] nums2 = {1, 2, 3, 4, 5};
System.out.println(solution.findSubarraysWithEqualSum(nums1)); // true
System.out.println(solution.findSubarraysWithEqualSum(nums2)); // false
}
}
This implementation ensures efficient time complexity while leveraging a HashSet to detect duplicate sums of subarrays.
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?