#2395

Find Subarrays With Equal Sum

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a hash set allows us to store the sums of subarrays of length 2 and check for duplicates efficiently. This reduces the time complexity significantly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty hash set to store the sums of subarrays.
  2. 2Step 2: Iterate through the array from index 0 to n-2.
  3. 3Step 3: For each index i, calculate the sum of the subarray nums[i] + nums[i+1].
  4. 4Step 4: Check if this sum already exists in the hash set. If it does, return true.
  5. 5Step 5: If not, add the sum to the hash set and continue.
  6. 6Step 6: If no duplicates are found after the loop, return false.
solution.py11 lines
1# Full working Python code
2nums = [4, 2, 4]
3def hasEqualSumSubarrays(nums):
4    seen = set()
5    for i in range(len(nums) - 1):
6        sum_subarray = nums[i] + nums[i + 1]
7        if sum_subarray in seen:
8            return True
9        seen.add(sum_subarray)
10    return False
11print(hasEqualSumSubarrays(nums))

Complexity note: The time complexity is O(n) because we only loop through the array once, calculating sums and checking the hash set in constant time. The space complexity is O(n) due to the storage of sums in the hash set.

  • 1Using a hash set allows for efficient duplicate checking.
  • 2Subarrays must start at different indices, which is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.