LeetCode 2395: Find Subarrays With Equal Sum

ArrayHash Table

Problem Description

Explanation:

To solve this problem, we can iterate through all possible pairs of subarrays of length 2 and check if their sum is equal. We need to make sure that the two subarrays start at different indices. We can achieve this by using two nested loops to select the starting indices of the two subarrays.

  • We iterate through all possible starting indices for the first subarray.
  • For each starting index of the first subarray, we iterate through all possible starting indices for the second subarray.
  • We calculate the sum of elements in each subarray and compare them. If we find a pair of subarrays with equal sums, we return true.
  • If we finish iterating through all possible pairs of subarrays without finding any equal sums, we return false.

Time Complexity:

The time complexity of this approach is O(n^2), where n is the length of the input array nums.

Space Complexity:

The space complexity is O(1) as we are not using any extra space.

:

Solutions

class Solution {
    public boolean findSubarraysWithEqualSum(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length - 1; j++) {
                if (nums[i] + nums[i + 1] == nums[j] + nums[j + 1]) {
                    return true;
                }
            }
        }
        return false;
    }
}

Loading editor...