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
-
[Reference: web.stanford.edu/class/archive/cs/cs106b/cs106b.1174/handouts/100%20Assignment%203.pdf]