Reputation: 81
I am aware that we do have space complexity difference between a recursive and iterative algorithm. But , do we also have time complexity differences between them? For example: If I have a program that counts the number of nodes in a list recursively and then I implement the same program as iterative, will I have any difference in its Time complexity i.e. O(n)? Thank you
Upvotes: 0
Views: 1517
Reputation: 6623
Short answer: no.
Unless you optimize the algorithm using dynamic programming or such, there is no change to time complexity. There is also no change to space complexity, don't know where you got that idea..
However, in many programming languages there is an inherent overhead to using recursion, since they must store the stack as well, which uses more memory. This can be slower, especially if it is not tail recursion.
Upvotes: 1