I was solving practice questions from a book when I stumbled upon this one :
*Describe a recursive algorithm that will check if an array A of integers contains an integer A[i] that is the sum of two integers that appear earlier in A, that is, such that
A[i] = A[j] +A[k] for j,k < i.
*
I have been thinking about this for a few hours but haven't been able to come up with a good recursive algorithm.
Method 1(Using Recursion) :Create a recursive function say, largest_element (int n, int arr[]). Base Condition : If(n==1) return arr[0]. ( If the remaining array is of length 1, return the only present element i.e. arr[0] ) Else, return max(arr[n-1], largest_element(n-1, arr))
A classic example of recursionThe factorial of a number is computed as that number times all of the numbers below it up to and including 1. For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .
A recursive solution without any loops (pseudocode):
bool check (A, i, j, k)
if (A[j] + A[k] == A[i])
return true
else
if (k + 1 < j) return check (A, i, j, k + 1)
else if (j + 1 < i) return check (A, i, j + 1, 0)
else if (i + 1 < A.size) return check (A, i + 1, 1, 0)
else return false
The recursive function is called with check(A, 2, 1, 0)
. To highlight the main part of the algorithm it does not check if the array initially has more than two elements.
Not very efficient but..
search(A, j, k) {
for (int i = 0; i < A.length; i++) {
if (A[i] == A[j] + A[k]) {
return i;
}
}
if (k + 1 == A.length) {
if (j + 1 < A.length) {
return search(A, j + 1, 0);
}
return -1; // not found
}
return search (A, j, k + 1);
}
Start the search with
search(A, 0, 0);
In python. The first function (search is less efficient O(n3)), but it also gives the j and k, the second one is more efficient (O(n2)), but only returns i.
def search(A, i):
for j in xrange(i):
for k in xrange(i):
if A[i] == (A[j] + A[k]):
return i, j, k
if i > 0:
return search(A, i - 1)
def search2(A, i, sums):
if A[i] in sums:
return i
if i == len(A) - 1:
return None
for j in range(i + 1):
sums.add(A[i] + A[j])
return search2(A, i + 1, sums)
if __name__ == '__main__':
print search([1, 4, 3], 2)
print search([1, 3, 4], 2)
print search2([1, 4, 3], 0, set())
print search2([1, 3, 4], 0, set())
It will print:
None
(2, 0, 1)
None
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With