Find Subarrays With Equal Sum - Problem

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.

Input & Output

Example 1 — Found Equal Sums
$ Input: nums = [4,2,4]
Output: true
💡 Note: We can take subarrays [4,2] (sum=6) and [2,4] (sum=6). Both have the same sum of 6.
Example 2 — No Equal Sums
$ Input: nums = [1,2,3,4]
Output: false
💡 Note: Subarrays are [1,2] (sum=3), [2,3] (sum=5), [3,4] (sum=7). All sums are different.
Example 3 — Too Short Array
$ Input: nums = [0,0]
Output: false
💡 Note: Only one subarray [0,0] possible, need at least two different subarrays.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Find Subarrays With Equal Sum INPUT nums = [4, 2, 4] 4 idx 0 2 idx 1 4 idx 2 Subarrays of Length 2: [4, 2] sum = 6 [2, 4] sum = 6 6 == 6 EQUAL SUMS FOUND! ALGORITHM STEPS 1 Initialize HashSet seen = { } 2 Process i=0 sum = 4+2 = 6 6 not in seen, add it seen = {6} 3 Process i=1 sum = 2+4 = 6 6 IS in seen! 4 Return Result Duplicate sum found return true Hash Set State 6 -- sum found twice FINAL RESULT Output: true Explanation: Two subarrays exist with equal sum of 6: [4,2] at idx 0 [2,4] at idx 1 Complexity Analysis Time: O(n) - single pass Space: O(n) - hash set Key Insight: Use a HashSet to track all seen subarray sums. For each pair of adjacent elements, compute the sum. If the sum already exists in the set, we found two subarrays with equal sum. Otherwise, add it to the set. TutorialsPoint - Find Subarrays With Equal Sum | Hash Set Approach
Asked in
Google 15 Amazon 12 Microsoft 8
24.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen