Find Subarrays With Equal Sum — LeetCode 2395 Python Solution

EasyArrayHash Table
Problem
#2395
Pattern
Hash Map
Reading time
2 min

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

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview