Q3 Vector STL#3 Predict the time complexity of the following recursive function, given the vector is of size N and the initial call is calSum(v, 0)

Q3. Vector STL#3
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);
}

How is the time complexity O(n^2)?

hello @ashutoshkabra3293

Its N^2 because vector is passed by value
So for each recursive call its copied to another new vector

N calls are there and in each call O(N) time is consumed in copying vector hence total complexity will be O(N*N)

So every time we do a call in any function is this overhead going to be there every time??

yeah if we pass by value.

we can improve it by passing it by refrence.

read diff b/w pass by value and pass by refrence

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.