LeetCode Problem Workspace

Find Subarrays With Equal Sum

Find Subarrays With Equal Sum is solved by scanning adjacent pairs and storing each length-2 sum in a hash set.

category

2

Topics

code_blocks

7

Code langs

hub

3

Related

Practice Focus

Easy · Array scanning plus hash lookup

bolt

Answer-first summary

Find Subarrays With Equal Sum is solved by scanning adjacent pairs and storing each length-2 sum in a hash set.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array scanning plus hash lookup

Try AiBox Copilotarrow_forward

For LeetCode 2395, compute the sum of every adjacent pair and track seen sums while scanning left to right. The moment a new length-2 subarray creates a sum already in the set, the answer is true because that sum came from a different start index. If the scan finishes without a repeat, return false.

Problem Statement

You are given a 0-indexed integer array nums. Decide whether two different subarrays of length 2 produce the same total, where different means the subarrays start at different indices.

Each valid check only looks at adjacent elements, so every candidate subarray is nums[i] and nums[i+1]. Return true as soon as any pair sum repeats, otherwise return false after checking all length-2 windows. For example, in nums = [4,2,4], the sums are 6 and 6, so the result is true.

Examples

Example 1

Input: nums = [4,2,4]

Output: true

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

No two subarrays of size 2 have the same sum.

Example 3

Input: nums = [0,0,0]

Output: true

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

Solution Approach

Scan every length-2 window once

This problem only cares about subarrays of size 2, so there is no reason to build larger windows or prefix-sum ranges. Loop from i = 0 to nums.length - 2 and compute nums[i] + nums[i+1] for each adjacent pair.

Store pair sums in a hash set

After computing each length-2 sum, check whether that sum was already seen from an earlier start index. If it was, return true immediately. Otherwise insert the sum and continue. This matches the Array plus Hash Table pattern directly and avoids comparing every pair of windows.

Return false if no repeat appears

If the scan ends without finding a duplicate pair sum, then no two length-2 subarrays share the same total. For nums = [4,2,4], the first window gives 6, the second window also gives 6, and the second check returns true on the spot.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

There are nums.length - 1 adjacent pairs, and each pair sum is inserted into or checked in the hash set once, so the time complexity is O(n). The hash set can hold up to n - 1 distinct length-2 sums, so the space complexity is O(n). A brute-force comparison of every pair of windows would waste work on this problem because the only target is repeated two-element sums.

What Interviewers Usually Probe

  • The interviewer emphasizes subarrays of fixed length 2, which usually means scan adjacent windows instead of using nested loops.
  • They mention different starting indices, which signals that equal content is allowed as long as the windows come from separate positions.
  • A hint about counting or tracking subarray sums points straight to a hash set or hash map keyed by each pair sum.

Common Pitfalls or Variants

Common pitfalls

  • Comparing subarrays themselves instead of comparing their length-2 sums adds unnecessary work and misses the actual requirement.
  • Forgetting that overlapping windows are allowed causes wrong answers on cases like [0,0,0], where both valid windows share elements.
  • Using an O(n^2) search over all window pairs solves small inputs but ignores the intended one-pass hash lookup pattern.

Follow-up variants

  • Count how many distinct length-2 sums appear more than once instead of returning a boolean.
  • Return the starting indices of the first two length-2 subarrays with equal sum rather than only true or false.
  • Generalize from size 2 to size k, where you would maintain a sliding window sum and still track repeated totals in a hash set.

FAQ

What is the key pattern in Find Subarrays With Equal Sum?

The core pattern is array scanning plus hash lookup. You compute each adjacent pair sum once and use a hash set to detect whether that exact length-2 sum appeared earlier.

Why does a duplicate sum guarantee the answer is true?

Each stored sum came from a specific starting index i. If the same sum appears again at a later index j, then two different length-2 subarrays have equal sum, which satisfies the condition.

Do the two subarrays need to be non-overlapping?

No. They only need to begin at different indices. Overlap is allowed, which is why [0,0,0] returns true from windows starting at indices 0 and 1.

Can this be solved without extra space?

Yes, you could compare every length-2 window against every later window, but that takes O(n^2) time. The hash-set solution uses extra space to keep the scan linear.

Why not use prefix sums for LeetCode 2395?

Prefix sums can compute window sums, but here every window already has fixed size 2, so nums[i] + nums[i+1] is simpler and clearer. A hash set on those direct sums is the most targeted solution for this problem.

terminal

Solution

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.

1
2
3
4
5
6
7
8
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
Find Subarrays With Equal Sum Solution: Array scanning plus hash lookup | LeetCode #2395 Easy