Find Subarrays With Equal Sum — LeetCode 2395 Python Solution
- Problem
- #2395
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [4,2,4]
- Output
- true
- Explanation
- The subarrays with elements [4,2] and [2,4] have the same sum of 6.
Python solution
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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the array nums auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2395. Find Subarrays With Equal Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2395. Find Subarrays With Equal Sum?
- LeetCode 2395. Find Subarrays With Equal Sum is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2395. Find Subarrays With Equal Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2395. Find Subarrays With Equal Sum?
- The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
- What topics does LeetCode 2395. Find Subarrays With Equal Sum cover?
- LeetCode 2395. Find Subarrays With Equal Sum is tagged Array and Hash Table on LeetCode.