Learn practical skills, build real-world projects, and advance your career
Created 2 years ago
Subarray with Given Sum
The following question was asked during a coding interview for Amazon:
You are given an array of numbers (non-negative). Find a continuous subarray of the list which adds up to a given sum.
# Solve the problem here
def sum_array(array,sum1):
for i in range(len(array)):
for j in range(i,len(array)+1):
if sum(array[i:j]) == sum1:
return i,j
return None,None
# Test the solution here
list1 = [1,7,4,2,1,3,11,5]
ls2 = sum_array(list1,10)
ls2
(2, 6)