Recursion

Practice Assignment

Note: Some of these problems can be solved using different other methods, but we would recommend you to use the method of recursion to solve these problems and get a better understanding of recursion.

Reversing a String (Beginner)

Write a function `reverseString(str)` that takes in a string argument and returns the reverse of the given string.
          
          _Input_ -> `"Calvin and Hobbes"` \
          _Output_ -> `"sebboH dna nivlaC"`
          

Greatest Common Divisor (GCD) (Beginner)

Write a function `gcd(a, b)` that takes in two numbers and returns the greatest common divisor of the two numbers.
          
          _Input_ -> `gcd(8, 12)` \
          _Output_ -> `4`
          
          _Input_ -> `gcd(15, 10)` \
          _Output_ -> `5`
          

nextIsDouble (Intermediate)

Write a function that takes a list, and return the number of elements in data that are followed directly by double that element.
          
          _Input_ -> `{1, 2, 4, 8, 16, 32, 64, 128, 256}` \
          _Output_ -> `8` \
          _Explanation_ -> The elements 1, 2, 4, 8, 16, 32, 64, and 128 are all followed directly by double their value. 
          
          _Input_ -> `{1, 0, 0, -5, -10, 32, 64, 128, 2, 9, 18}` \
          _Output_ -> `5` \
          _Explanation_ -> The elements 0, -5, 32, 64 and 9 are all followed directly by double their value.
          

MaxConsecutiveSum (Advanced)

Write a function `maxConsecutiveSum(arr)` that takes a list of integers as input and returns the maximum sum of consecutive elements in the list. Consecutive elements are elements that appear in sequence without any gaps.
          
          _Input_ -> `maxConsecutiveSum([1, -2, 3, 4, -1, 2, 1, -5, 4])` \
          _Output_ -> `9` \
          _Explanation_ -> The maximum sum of consecutive elements in the list is 9. The consecutive elements are 3, 4, -1, 2, 1.
          
          _Input_ -> `maxConsecutiveSum([2, -3, 4, -1, -2, 1, 5, -3])` \
          _Output_ -> `8` \
          _Explanation_ -> The maximum sum of consecutive elements in the list is 8. The consecutive elements are 4, -1, -2, 1, 5.
          

Binary Search (Advanced)

Write a function binarySearch(data, target) that takes in a sorted list and a target value and returns the index of the target value in the list. If the target value is not present in the list, return -1.
          
          _Input_ -> `binarySearch({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5)` \
          _Output_ -> `4`
          
          _Input_ -> `binarySearch({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 11)` \
          _Output_ -> `-1`