Find Subarray with Given Sum | Set 1 (Nonnegative Numbers) in Ruby
This guide will walk you through how to implement a method that checks the sum of every subarray one by one in order to find a subarray that equals the sum given.
Guide Tasks
  • 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.

Test Cases

Code File