Learn practical skills, build real-world projects, and advance your career

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.

alt

# Solve the problem here
def subarr_sum(arr, target):
    n = len(arr)
    for i in range(n):
        for j in range(i, n+1):
            if sum(arr[i:j]) == target:
                return i, j
    return None, None
# Test the solution here
arr1 = [1, 7, 4, 2, 1, 3, 11, 5]
target1 = 10
i, j = subarr_sum(arr1, target1)
i, j, arr1[i:j]
(2, 6, [4, 2, 1, 3])