Time complexity = k * O(1) = O(logn)* O(1) = O(logn) So loop will run O(logn) number of times and doing O(1) operation at each step. Let’s assume the loop will terminate after k steps where the loop variable increases or decreases by a factor of 2. Thus, we need to count the total number of iterations performed by the loop to calculate the time complexity. Here loop is running in the range of 1 to n, and the loop variable increases or decreases by a factor of 2 at each step. So time complexity = n*O(1) = O(n)Ī loop incrementing/decrementing by a constant factor: O(logn) //example 1 Time complexity = n*O(1) = O(n)*O(1) = O(n)Ī loop running constant multiple of n times: O(n) for (int i = 1 i r. Here both loops are running some n times and performing O(1) operation at each iteration of the loop. Time complexity analysis of a single loopĪ loop running constant times: O(1) for (int i = 1 i 0 i = i - c) Let’s analyze the time complexity of the various loop pattern. Representing this expression in terms of Big-O notation will give the time complexity of the loop.
The time complexity of loop = (count of loop iterations in the worst case) * (time complexity of the code in the loop body).This code may contain conditional statements, comparison operation, swapping operation, assignment operation, etc. Calculating the time complexity of the code in the loop body- loop execute this code on each iteration to get the final result.Most of the time loop will be running for each data element or total input size. Counting the total loop iteration in the worst case - we can get this insight from considering the worst-case scenario, initial and final value of the loop variable, loop condition, and increment or decrement operation.
Steps to analyse the time complexity of the loop After some basic practice of various loop patterns, we can make optimization decisions quickly and save a lot of analysis time. Learning time complexity analysis of loops is not difficult. One idea would be simple: to design a better algorithm or optimize the code further, we should learn to analyze the time complexity of the loop in terms of Big-O notation. Nested loops: two nested loops, three nested loops, single loop with nested loops.
Single loop: loop running constant time, a loop is running n times, loop growing exponentially, a loop running based on the specific condition, a loop running with data structure, consecutive single loops, etc.These two loop patterns appear frequently in our solutions: So the efficiency of such an algorithm depends on the loop structure and operations inside the loop. Moreover, some problem-solving approaches are purely based on loop-building partial solutions using a single loop, two-pointers approach, sliding window approach, BFS traversal, bottom-up approach of dynamic programming, problem-solving using stack, etc. A lot of coding problem solutions involve various kinds of loop structures. Loop is a fundamental problem-solving operation in programming.