- Read Tutorial
- Complete the Exercise
Summary
Build a method that finds a continuous subarray which adds to equal a given number.
Exercise Description
Define a method that loops through each element in an array and determines if there is a subarray that adds up to equal a given number. Each element should add on to each other until the expected number is achieved. If the subarray sum exceeds the given number, you need to figure out how to bypass the first element and loop through the array again. If no subarray sum could be found, return a notification stating the fact.
Example Data
# Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 # => Sum found between indexes 2 and 4 # Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7 # => Sum found between indexes 1 and 4 # Input: arr[] = {1, 4}, sum = 0 # => No subarray found
Real World Usage
This exercise is fairly complex and will test your knowledge of loops as well as help you discover that there are many ways, some better than others, to implement a method to achieve a solution. In addition, this can also be helpful when it comes to building algorithms.