Question:
How to return the subarray indexes from left to right using Java

Summary

Let's assume:

Array- A

Integer- N

Function

subarraySum()


Solution


class Solution

{

    //Function to find a continuous sub-array which adds up to a given number.

    static ArrayList<Integer> subarraySum(int[] arr, int n, int sum) 

    {

        // Your code here

        ArrayList<Integer> ans=new ArrayList<>();

        int p1=0;

        int temp_sum=0;

        for(int i=0;i<n;i++){

            temp_sum+=arr[i];

            while(temp_sum>sum && p1<i){

                temp_sum-=arr[p1];

                p1++;

            }

            if(temp_sum==sum){

                

                ans.add(p1+1);

                ans.add(i+1);

                return ans;

            }

        }

        ans.add(-1);

        return ans;

    }

}


Suggested blogs:

>>How can I specify a monkey-patched class in the typescript definitions file in JavaScript?

>>How to merge an object into Array of an objects with the same key in JavaScript?

>>How to make one JavaScript event wait for another to trigger?

>>How to manipulate Array object in JavaScript?

>>How to do light and dark mode in a website using HTML and JavaScript?


Nisha Patel

Nisha Patel

Submit
0 Answers