Leetcode 2395. Find Subarrays With Equal Sum
You are 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 start at different indices.
Formally, return true if there exist two indices i
and j
(i != j
) such that nums[i] + nums[i + 1] == nums[j] + nums[j + 1]
, and return false otherwise.
#include <iostream>
#include <vector>
#include <unordered_set>
bool findSubarraysWithEqualSum(const std::vector<int>& nums) {
std::unordered_set<int> sums;
for (size_t i = 0; i < nums.size() - 1; ++i) {
int sum = nums[i] + nums[i + 1];
if (sums.find(sum) != sums.end()) {
return true;
}
sums.insert(sum);
}
return false;
}
// Example usage
int main() {
std::vector<int> nums1 = {4, 2, 4};
std::vector<int> nums2 = {1, 2, 3, 4, 5};
std::cout << std::boolalpha;
std::cout << "Test case 1: " << findSubarraysWithEqualSum(nums1) << std::endl; // Output: true
std::cout << "Test case 2: " << findSubarraysWithEqualSum(nums2) << std::endl; // Output: false
return 0;
}
This solution efficiently identifies whether there exist two subarrays with equal sums by leveraging a set to track previously encountered sums, ensuring quick look-up times.
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?