Interview Question
Country: United States
Nice and clean solution, though it requires the programmer to know the size of the array (at compile time), as there is no bounds checking.
Use tail recursion. Plain recursion is inefficient and most likely will blow up the stack. The following code allows tail recursion optimization (with option -O2 at least in gcc), try it, it won't blow up.
#include <stdio.h>
#include <stdlib.h>
int tailSum(int*buf, int n, int sum) {
if (n == 0)
return sum;
return tailSum(buf + 1, n - 1, sum + buf[0]);
}
int main() {
int *buf = (int*)malloc(sizeof(int) * 1000000);
// initialize buf contents
printf("%d\n", tailSum(buf, 1000000, 0));
return 0;
}
Could you tell me Why are you decrementing n value while you are incrementing buf to buf+1;,
One side it is incremented and another side decremented .Half array sum will be calculated..?
Please let me know.
Tail recursive algorithm.
private long subarraySum( int[] arr, int from, int to, long res ){
if( from > to ){
throw new IllegalArgumentException("from > to: " + from + " > " + to);
}
if( from < 0 || from >= arr.length || to >= arr.length ){
throw new IllegalArgumentException("'from' or 'to' is incorrect");
}
if( from == to ){
return res + arr[to];
}
return subarraySum( arr, from+1, to, res + arr[from] );
}
My instinct for this problem is ... interviewer is trying test some wide range of data structure and algorithm that we should know. It obviously needs preprocessing to avoid loop for range sum. This is sum range problem. Cumulutive sum or prefix sum gives us solution in O(n) preprocessing time but O(1) query time. However with segment tree preporcessing it will be <O(log n ) , O(logn)>
#include <functional>
#include <numeric>
long sum(int i, int j, int [] numbers)
{
return accumulate(numbers,numbers+abs(i-j)+1,0);
}
@Abhi : It looks you have never read mathematics. You use re-cursion in simple summation program. Looks you are just a school student. Your method is most inefficient method. In my solution it was just a typo : "%" ... i meant, division that is "/" .
Ok Dear : Solve the below condition
Array content = {10,56,17,23,99,819}
starting index = 1;
ending index = 4;
Answer = 56+17+23+99
@Bijendra : You are making an assumption that array would be having sequential elements from i to j, which is not the case here. I agree with @abhi that you have no idea what is going on :)
Use Recursion : Pass the value of the range and keep increasing the range
- Abhi January 27, 2013