I need an algorithm to determine if an array contains two elements that sum to a given integer.
The array is sorted.
The algorithm should be recursiv
It is pretty easy. It is important for array to be sorted.
Correct algorithm with O(n) time complexity and no additional space is:
public static boolean isContainsSum(int[] arr, int sum) {
for (int i = 0, j = arr.length - 1; i < j; ) {
if (arr[i] + arr[j] == sum)
return true;
if (arr[i] + arr[j] < sum)
i++;
else
j--;
}
return false;
}
To make it recursive, you need just replace i
and j
iterations with recursive call:
public static boolean isContainsSumRecursive(int[] arr, int sum) {
return isContainsSumRecursive(arr, sum, 0, arr.length - 1);
}
private static boolean isContainsSumRecursive(int[] arr, int sum, int i, int j) {
if (i == j)
return false;
if (arr[i] + arr[j] == sum)
return true;
if (arr[i] + arr[j] < sum)
return isContainsSumRecursive(arr, sum, i + 1, j);
return isContainsSumRecursive(arr, sum, i, j - 1);
}