Predict the time complexity of the following recursive function, given the vector is of size N and the initial call is calSum(v, 0).
int sum = 0;
void calcSum(vector v, int i)
{
if(i == v.size())
return;
sum += v[i];
calcSum(v, i+1);
}
Predict the time complexity of the following recursive function, given the vector is of size N and the initial call is calSum(v, 0).
int sum = 0;
void calcSum(vector v, int i)
{
if(i == v.size())
return;
sum += v[i];
calcSum(v, i+1);
}
@nemishgarg1999
assumming vector is defined as vector< int > v
its time complexity will be O(n^2).
because total n calls wiil be there and on every call vector get copied to new vector which is O(n) for each call . therefore O(n^2) for n calls
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
If we use simply array instead of vector, then what would be the time complexity in this case?
@nemishgarg1999
it will be O(n) in case of array because then we will be passing pointer and not the whole array
Why can’t we pass pointer in case of vector?
@nemishgarg1999
we can pass vector as reference ( very similar to pointer)
check this article-> https://www.geeksforgeeks.org/passing-vector-function-cpp/
Thanks my doubt is also clear now