Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity difference in Linkedlist implementation (Iterative VS Recursive)?

Does the time complexity change in these two implementation of getting the count of nodes in a Linkedlist ?

 private int getCountIterative() {

    Node start = head;
    int count = 0;
    while (start != null)
    {
        count++;
        start = start.next;
    }
    return count;
}


private int getCountRecursive(Node node) {
    if (node == null)
        return 0;
    return 1 + getCountRecursive(node.next);
}
like image 779
Spark Avatar asked Jan 10 '19 21:01

Spark


People also ask

What is faster iterative or recursive?

Strengths: Iteration can be used to repeatedly execute a set of statements without the overhead of function calls and without using stack memory. Iteration is faster and more efficient than recursion. It's easier to optimize iterative codes, and they generally have polynomial time complexity.

What is the difference between recursive and iterative?

Recursion is when a statement in a function calls itself repeatedly. The iteration is when a loop repeatedly executes until the controlling condition becomes false.

What is the time complexity of insertion in Linkedlist?

Each insert operation should take O(1) time complexity.

What is the time complexity of recursion?

The time complexity of recursion depends on two factors: 1) Total number of recursive calls 2) Time complexity of additional operations for each recursive call. So recursion tree is a diagram to represent the additional cost for each recursive call in terms of input size n.


2 Answers

No, the time complexity won't change.

However the performance and overall run time will usually be worse for recursive solution because Java doesn't perform Tail Call Optimization.

like image 145
Karol Dowbecki Avatar answered Oct 19 '22 00:10

Karol Dowbecki


TL;DR: it's the same complexitiy

To calculate the complexity of an operation (like a search or sort algorithm - or your example, the count), you need to identify the dominating operation.

For searching and sorting, it's usually comparisons. What is your dominating operation? Let's assume it's node.next, the lookup of the next node.

Then, both approaches have O(n) operations - so it's the same complexity.

Please be aware that this time complexity is a simplification. There are factors ignored, like the overhead of function calls. So, it's the same complexity, but that doesn't necessarily tell you which version is faster.

like image 38
Jörg Beyer Avatar answered Oct 19 '22 00:10

Jörg Beyer