# Find SubArray with given Sum in Python

Hi, guys, we are given with the array or list in Python. Our task is to **Find a subarray with given sum in Python.**

You all should know about the subarray before attempting the given question. So I advise checking “What is a subarray?”

**Algorithm part:-**

- Make a function name
**find**and pass the**array, length of the given array and the sum to find in the array**. - Run a loop from 0 to length of the array.
- Take a variable name currsum and assign the first element of the array.
- now take a variable j and make it i+1
- Now if the j is less than or equal to n the while loop will run.
- If currsum is greate than the given sum or j is equal to n the break the loop or currsum is equal to given sum the print the indexes.
- If the above conditions are not satisfied.

Then add the next element to the currsum.

## Python program: Find SubArray with given Sum

Now here is the code

def subsum(arr,n,sum): for i in range(n): currsum=arr[i] j=i+1 while j<=n: if currsum==sum: print ("Sum found between") print("indexes %d and %d"%( i, j-1)) return 1 if currsum>sum or j==n: break currsum=currsum+arr[j] j+=1 print ("No subarray found") return 0 # Driver program print("Enter the array") arr=list(map(int,input().split(" "))) n=len(arr) sum=int(input("Enter the sum to find in the array\n")) subsum(arr,n,sum)

Here is the output:-

## Leave a Reply

You must be logged in to post a comment.