0

I am trying to create a continuous subArray from a given array which is equal to the given sum and return the first and last index as an ArrayList. This is the solution i could think of which actually passed 52 testcases but failed for a really large set of Arrays where it is returning -1 instead. Input - arr = {1,2,3,7,5} n = 5 s = 12Expected output = 2, 4

static ArrayList<Integer> subarraySum(int[] arr, int n, int s) {
    ArrayList<Integer> result = new ArrayList<>();
    result.add(0, -1);
    for (int i = 0; i < n; i++) {
        int sum = arr[i];
        for (int j = i+1; j < n; j++) {
            sum += arr[j];
            if (sum == s) {
                result.add(1, j+1);
                result.set(0, i+1);
                return result;
            }
        }
    }
    return result;
}
  • This looks like a problem from a programming practice or challenge site. Please provide a link to the page that presents the problem. – Old Dog Programmer Mar 31 '23 at 18:10
  • By the way, and off-topic: In Java, an array is a reference type, and has its own `length` attribute. – Old Dog Programmer Mar 31 '23 at 19:00
  • 1
    code does not *consider* a one element sub-array. What will happen if only one single value is equal to the sum? Example `{1,2,3}` and `sum=2` or even trivial `{1}` and `sum=1` (@OldDogProgrammer based on sample data, the array is not sorted; and the problem is probably stated for different languages, not just Java [my guess], so not using `length`) – user16320675 Mar 31 '23 at 19:03
  • 1
    https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1?page=1&difficulty[]=0&category[]=Arrays&sortBy=submissions this is the link to the problem @OldDogProgrammer – Sourav Borah Apr 04 '23 at 18:53
  • I noticed the authors of the problem want it done in O(n). Your program runs in O(n^2). You said your code failed for a really large set of arrays. Did your code fail because it returned the wrong answer or did it fail because it took too long to run? – Old Dog Programmer Apr 04 '23 at 23:50

1 Answers1

0

The following code should work:

static ArrayList<Integer> subarraySum(int[] arr, int s) {
    ArrayList<Integer> result = new ArrayList<>();
    
    for (int i = 0; i < arr.length; i++) {
        int sum = 0;
        for (int j = i; j < arr.length; j++) {
            sum += arr[j];
            
            if (s == sum) {
                result.add(i+1);
                result.add(j+1);
                return result;
            }
        }
    }
    
    result.add(-1);
    return result;
}
Johann Schwarze
  • 161
  • 1
  • 4