Skip to content

2395. Find Subarrays With Equal Sum 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  bool findSubarrays(vector<int>& nums) {
    unordered_set<int> seen;

    for (int i = 1; i < nums.size(); ++i)
      if (!seen.insert(nums[i - 1] + nums[i]).second)
        return true;

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean findSubarrays(int[] nums) {
    Set<Integer> seen = new HashSet<>();

    for (int i = 1; i < nums.length; ++i) {
      final int sum = nums[i - 1] + nums[i];
      if (seen.contains(sum))
        return true;
      seen.add(sum);
    }

    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def findSubarrays(self, nums: list[int]) -> bool:
    seen = set()

    for a, b in zip(nums, nums[1:]):
      summ = a + b
      if summ in seen:
        return True
      seen.add(summ)

    return False