2

I am trying to find the number of sub arrays which equals to a given sum K. For example, when I have an arr = [1, -1, 1, -1, 1], I created a new array such that:

        int[] s = new int[arraySize + 1];

        s[0] = 0;

        for (int i = 1; i <= arraySize; i++) {
            s[i] = s[i - 1] + arr[i - 1];
        }

Which gives me:

s[0] = 0
s[1] = arr[0] 
s[2] = arr[0] + arr[1]
s[3] = arr[0] + arr[1] + arr[2]
s[4] = arr[0] + arr[1] + arr[2] + arr[3]
s[5] = arr[0] + arr[1] + arr[2] + arr[3] + arr[4]

To calculate the subarrays that add up to sum K = 0:

        for (int i = arraySize; i > 0; i--) {
            for (int j = i; j > 0; j--) {
                if (subArrays[i] - subArrays[j - 1] == 0) {
                    counter++;
                }
                else {
                    continue;
                }
            }
        }

Which returns me the correct output = 6 possible sub arrays

However, is there a way to improve the time complexity such that it takes less than O(n^2) as shown in the above method? (Without using map or hashmap)

python
  • 43
  • 4

0 Answers0