Find Subarrays With Equal Sum - Problem
Find Subarrays With Equal Sum

You're given a 0-indexed integer array nums. Your task is to determine whether there exist two subarrays of length 2 with equal sum.

๐ŸŽฏ Key Points:
โ€ข Both subarrays must have exactly 2 elements
โ€ข They must begin at different indices
โ€ข A subarray is a contiguous sequence of elements

Goal: Return true if such subarrays exist, false otherwise.

Example: In array [4,2,4], we have subarrays [4,2] (sum=6) and [2,4] (sum=6), so return true.

Input & Output

example_1.py โ€” Basic Case
$ Input: [4,2,4]
โ€บ Output: true
๐Ÿ’ก Note: We have two subarrays: [4,2] starting at index 0 with sum 6, and [2,4] starting at index 1 with sum 6. Since both sums are equal and start at different indices, return true.
example_2.py โ€” No Equal Sums
$ Input: [1,2,3,4,5]
โ€บ Output: false
๐Ÿ’ก Note: The subarrays are: [1,2]=3, [2,3]=5, [3,4]=7, [4,5]=9. All sums are different, so no two subarrays have equal sum. Return false.
example_3.py โ€” Minimum Length
$ Input: [0,0,0]
โ€บ Output: true
๐Ÿ’ก Note: We have subarrays [0,0] starting at index 0 with sum 0, and [0,0] starting at index 1 with sum 0. Both have equal sum, so return true.

Constraints

  • 2 โ‰ค nums.length โ‰ค 1000
  • -109 โ‰ค nums[i] โ‰ค 109
  • Must have at least 2 elements to form length-2 subarrays

Visualization

Tap to expand
Hash Set Pattern Recognition๐Ÿง  Memory Game AnalogyLike playing memory: You flip cards (calculate sums) and remember what you've seen.When you find a match (duplicate sum), you win! No need to flip remaining cards.๐ŸŽฎ Strategy: Remember efficiently using hash set instead of comparing all pairsStep-by-Step Process1Start with empty hash set { }2Calculate [4,2] sum = 636 not seen before โ†’ add to set {6}4Calculate [2,4] sum = 656 already in set โ†’ MATCH! Return true๐ŸŽ‰ Early termination saves time!Visual Memory[4,2]sum=6[2,4]sum=6MATCH!Hash Set Contents6โ† Duplicate detected!O(1) lookup time makes this efficient
Understanding the Visualization
1
Scan Array
Move through array calculating adjacent pair sums
2
Check Memory
See if current sum was encountered before
3
Update Memory
Add new sum to memory if not seen
4
Early Exit
Return true immediately when duplicate found
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide O(1) average lookup time, making duplicate detection extremely efficient. This transforms a quadratic comparison problem into a linear scanning problem with early termination.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
32.4K 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