In this particular case, the time complexity remains the same for both approaches, but an extra loop increases the number of operations. In the case of a loop, the loop itself has some operations to perform, e.g., initialization (one time), condition check (in each iteration), and increment/decrement (in each iteration). An extra loop definitely increases the number of operations. In the naive approach, we are using a loop to find the number of nodes that perform n operations of traversing the LinkedList. In this case, this loop performs the following operations:
- Loop variable initialization: 1
- Loop condition checks: n
- Loop increments: n
- Traversing list: n
Total: 3n+1
In the second loop of the naive approach, we are iterating the list to k nodes (assuming the nth last node is k) and updating the next
address of the kth node. The operations of the second loop are as follows:
- Loop variable initialization: 1
- Loop condition checks: k
- Loop increments: k
- Traversing list: k
- Updating address: 1
Total: 3k+2
Total operations for the naive approach are: 3n+1+3k+2 = 3n+3k+3
In the case of the optimized approach, we are using a single loop, updating 2 pointers and updating the next
address. The operations of these loops are as follows:
- Loop variable initialization: 1
- Loop condition checks: n
- Loop increments: n
- Traversing list (updating pointers): n+k
- Updating address: 1
Total: 3n+k+2
Total operations for the optimized approach are: 3n+k+2
If we compare the number of operations, we can see the difference of 2k+1 operations. Although time complexity in terms of big-O will be the same for both approaches, but the number of operations will be less in the optimized approach. I hope you understand how a loop impacts the number of operations. If you’ve any other queries, do let us know. Thanks!