How to Analyse Loops for Complexity Analysis of Algorithms
Last Updated :
23 Jul, 2025
We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed.
The analysis of loops for the complexity analysis of algorithms involves finding the number of operations performed by a loop as a function of the input size. This is usually done by determining the number of iterations of the loop and the number of operations performed in each iteration.
Here are the general steps to analyze loops for complexity analysis:
Determine the number of iterations of the loop. This is usually done by analyzing the loop control variables and the loop termination condition.
Determine the number of operations performed in each iteration of the loop. This can include both arithmetic operations and data access operations, such as array accesses or memory accesses.
Express the total number of operations performed by the loop as a function of the input size. This may involve using mathematical expressions or finding a closed-form expression for the number of operations performed by the loop.
Determine the order of growth of the expression for the number of operations performed by the loop. This can be done by using techniques such as big O notation or by finding the dominant term and ignoring lower-order terms.
Constant Time Complexity O(1):
The time complexity of a function (or set of statements) is considered as O(1) if it doesn't contain a loop, recursion, and call to any other non-constant time function.
i.e. set of non-recursive and non-loop statements
In computer science, O(1) refers to constant time complexity, which means that the running time of an algorithm remains constant and does not depend on the size of the input. This means that the execution time of an O(1) algorithm will always take the same amount of time regardless of the input size. An example of an O(1) algorithm is accessing an element in an array using an index.
Example:
- swap() function has O(1) time complexity.
- A loop or recursion that runs a constant number of times is also considered O(1). For example, the following loop is O(1).
C++
// Here c is a positive constant
for (int i = 1; i <= c; i++) {
// some O(1) expressions
}
//This code is contributed by Kshitij
C
// Here c is a constant
for (int i = 1; i <= c; i++) {
// some O(1) expressions
}
Java
// Here c is a constant
for (int i = 1; i <= c; i++) {
// some O(1) expressions
}
// This code is contributed by Utkarsh
C#
// Here c is a positive constant
for (int i = 1; i <= c; i++) {
// This loop runs 'c' times and performs some constant-time operations in each iteration
// The time complexity of the loop is O(c)
// The time complexity of the loop body is O(1)
// The overall time complexity of this code is O(c)
// Note that the loop starts at i=1 and goes up to i=c (inclusive)
// The loop variable i is incremented by 1 in each iteration
// Example of an O(1) expression: int x = 1 + 2; // this takes constant time
}
JavaScript
// Here c is a constant
for (var i = 1; i <= c; i++) {
// some O(1) expressions
}
Python3
# Here c is a constant
for i in range(1, c+1):
# some O(1) expressions
# This code is contributed by Pushpesh Raj.
Linear Time Complexity O(n):
The Time Complexity of a loop is considered as O(n) if the loop variables are incremented/decremented by a constant amount. For example following functions have O(n) time complexity. Linear time complexity, denoted as O(n), is a measure of the growth of the running time of an algorithm proportional to the size of the input. In an O(n) algorithm, the running time increases linearly with the size of the input. For example, searching for an element in an unsorted array or iterating through an array and performing a constant amount of work for each element would be O(n) operations. In simple words, for an input of size n, the algorithm takes n steps to complete the operation.
C++
// Here c is a positive integer constant
for (int i = 1; i <= n; i = i + c) {
// some O(1) expressions
}
for (int i = n; i > 0; i = i - c) {
// some O(1) expressions
}
// This code is contributed by Kshitij
C
// Here c is a positive integer constant
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
for (int i = n; i > 0; i -= c) {
// some O(1) expressions
}
Java
// Here c is a positive integer constant
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
for (int i = n; i > 0; i -= c) {
// some O(1) expressions
}
// This code is contributed by Utkarsh
C#
for (int i = 1; i <= n; i = i + c) {
// some O(1) expressions
// O(1) expressions could be computations, assignments,
// or other constant time operations
}
// Second loop: Decrementing by 'c' from n to 1
for (int i = n; i > 0; i = i - c) {
// some O(1) expressions
// O(1) expressions could be computations, assignments,
// or other constant time operations
}
JavaScript
// Here c is a positive integer constant
for (var i = 1; i <= n; i += c) {
// some O(1) expressions
}
for (var i = n; i > 0; i -= c) {
// some O(1) expressions
}
Python3
# Here c is a positive integer constant
for i in range(1, n+1, c):
# some O(1) expressions
for i in range(n, 0, -c):
# some O(1) expressions
# This code is contributed by Pushpesh Raj
Quadratic Time Complexity O(nc):
The time complexity is defined as an algorithm whose performance is directly proportional to the squared size of the input data, as in nested loops it is equal to the number of times the innermost statement is executed. For example, the following sample loops have O(n2) time complexity
Quadratic time complexity, denoted as O(n^2), refers to an algorithm whose running time increases proportional to the square of the size of the input. In other words, for an input of size n, the algorithm takes n * n steps to complete the operation. An example of an O(n^2) algorithm is a nested loop that iterates over the entire input for each element, performing a constant amount of work for each iteration. This results in a total of n * n iterations, making the running time quadratic in the size of the input.
C++
// Here c is any positive constant
for (int i = 1; i <= n; i += c) {
for (int j = 1; j <= n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i -= c) {
for (int j = i + 1; j <= n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i -= c) {
for (int j = i - 1; j > 0; j -= c) {
// some O(1) expressions
}
}
// This code is contributed by Kshitij
C
for (int i = 1; i <= n; i += c) {
for (int j = 1; j <= n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i -= c) {
for (int j = i + 1; j <= n; j += c) {
// some O(1) expressions
}
}
Java
for (int i = 1; i <= n; i += c) {
for (int j = 1; j <= n; j += c) {
// some O(1) expressions
}
}
for (int i = n; i > 0; i -= c) {
for (int j = i + 1; j <= n; j += c) {
// some O(1) expressions
}
}
// This code is contributed by Utkarsh
C#
using System;
class Program {
static void Main()
{
// Here c is any positive constant
int n = 10; // You can replace 10 with your desired
// value of 'n'
int c = 2; // You can replace 2 with your desired
// value of 'c'
// First loop
for (int i = 1; i <= n; i += c) {
for (int j = 1; j <= n; j += c) {
// some O(1) expressions
Console.WriteLine("Expression at (" + i
+ ", " + j + ")");
}
}
// Second loop
for (int i = n; i > 0; i -= c) {
for (int j = i + 1; j <= n; j += c) {
// some O(1) expressions
Console.WriteLine("Expression at (" + i
+ ", " + j + ")");
}
}
// Third loop
for (int i = n; i > 0; i -= c) {
for (int j = i - 1; j > 0; j -= c) {
// some O(1) expressions
Console.WriteLine("Expression at (" + i
+ ", " + j + ")");
}
}
}
}
JavaScript
for (var i = 1; i <= n; i += c) {
for (var j = 1; j <= n; j += c) {
// some O(1) expressions
}
}
for (var i = n; i > 0; i -= c) {
for (var j = i + 1; j <= n; j += c) {
// some O(1) expressions
}
}
Python3
for i in range(1, n+1, c):
for j in range(1, n+1, c):
# some O(1) expressions
for i in range(n, 0, -c):
for j in range(i+1, n+1, c):
# some O(1) expressions
# This code is contributed by Pushpesh Raj
Example: Selection sort and Insertion Sort have O(n2) time complexity.
The time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive calls in the recursive function, the Time Complexity is considered as O(Logn).
C++
for (int i = 1; i <= n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
// This code is contributed by Kshitij
C
for (int i = 1; i <= n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
Java
for (int i = 1; i <= n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
// This code is contributed by Utkarsh
C#
using System;
class Program {
static void Main(string[] args)
{
int n = 10; // assuming n is some integer value
int c = 2; // assuming c is some integer value
// Loop to iterate through powers of c up to n
for (int i = 1; i <= n; i *= c) {
// O(1) expressions here
Console.WriteLine("i = " + i);
}
// Loop to iterate through powers of c down from n
for (int i = n; i > 0; i /= c) {
// O(1) expressions here
Console.WriteLine("i = " + i);
}
}
}
JavaScript
for (var i = 1; i <= n; i *= c) {
// some O(1) expressions
}
for (var i = n; i > 0; i /= c) {
// some O(1) expressions
}
Python3
i = 1
while(i <= n):
# some O(1) expressions
i = i*c
i = n
while(i > 0):
# some O(1) expressions
i = i//c
# This code is contributed by Pushpesh Raj
C++
// Recursive function
void recurse(int n)
{
if (n <= 0)
return;
else {
// some O(1) expressions
}
recurse(n/c);
// Here c is positive integer constant greater than 1
}
// This code is contributed by Kshitij
C
// Recursive function
void recurse(int n)
{
if (n <= 0)
return;
else {
// some O(1) expressions
}
recurse(n/c);
// Here c is positive integer constant greater than 1
}
Java
// Recursive function
void recurse(int n)
{
if (n <= 0)
return;
else {
// some O(1) expressions
}
recurse(n/c);
// Here c is positive integer constant greater than 1
}
// This code is contributed by Utkarsh
C#
using System;
class Program {
// Recursive function
static void Recurse(int n, int c)
{
// Base case: If n is less than or equal to 0,
// return
if (n <= 0)
return;
else {
// Perform some O(1) expressions
// Recursive call with updated parameter (n/c)
Recurse(n / c, c);
}
}
static void Main()
{
int n = 10; // Example value for n
int c = 2; // Example value for c
// Function Call
Recurse(n, c);
Console.WriteLine("Recursive function executed.");
}
}
JavaScript
// Recursive function
function recurse(n)
{
if (n <= 0)
return;
else {
// some O(1) expressions
}
recurse(n/c);
// Here c is positive integer constant greater than 1
}
Python3
# Recursive function
def recurse(n):
if(n <= 0):
return
else:
# some O(1) expressions
recurse(n/c)
# Here c is positive integer constant greater than 1
# This code is contributed by Pushpesh Raj
Example: Binary Search(refer iterative implementation) has O(Logn) time complexity.
Logarithmic Time Complexity O(Log Log n):
The Time Complexity of a loop is considered as O(LogLogn) if the loop variables are reduced/increased exponentially by a constant amount.
C++
// Here c is a constant greater than 1
for (int i = 2; i <= n; i = pow(i, c)) {
// some O(1) expressions
}
// Here fun() is sqrt or cuberoot or any other constant root
for (int i = n; i > 1; i = fun(i)) {
// some O(1) expressions
}
//This code is contributed by Kshitij
C
// Here c is a constant greater than 1
for (int i = 2; i <= n; i = pow(i, c)) {
// some O(1) expressions
}
// Here fun is sqrt or cuberoot or any other constant root
for (int i = n; i > 1; i = fun(i)) {
// some O(1) expressions
}
Java
// Here c is a constant greater than 1
for (int i = 2; i <= n; i = Math.pow(i, c)) {
// some O(1) expressions
}
// Here fun is sqrt or cuberoot or any other constant root
for (int i = n; i > 1; i = fun(i)) {
// some O(1) expressions
}
// This code is contributed by Utkarsh
C#
using System;
public class Main
{
public static void Execute(string[] args)
{
int n = 100; // Example value of n
int c = 2; // Example value of c
// Here c is a constant greater than 1
for (int i = 2; i <= n; i = (int)Math.Pow(i, c))
{
// some O(1) expressions
Console.WriteLine(i); // For demonstration
}
// Here fun() is sqrt or cuberoot or any other constant root
for (int i = n; i > 1; i = fun(i))
{
// some O(1) expressions
Console.WriteLine(i); // For demonstration
}
}
// Function to find constant root (e.g., sqrt, cuberoot)
public static int fun(int num)
{
// Here, let's consider finding the square root
return (int)Math.Sqrt(num);
}
}
JavaScript
// Here c is a constant greater than 1
for (var i = 2; i <= n; i = i**c) {
// some O(1) expressions
}
// Here fun is sqrt or cuberoot or any other constant root
for (var i = n; i > 1; i = fun(i)) {
// some O(1) expressions
}
Python3
# Here c is a constant greater than 1
i = 2
while(i <= n):
# some O(1) expressions
i = i**c
# Here fun is sqrt or cuberoot or any other constant root
i = n
while(i > 1):
# some O(1) expressions
i = fun(i)
# This code is contributed by Pushpesh Raj
See this for mathematical details.
How to combine the time complexities of consecutive loops?
When there are consecutive loops, we calculate time complexity as a sum of the time complexities of individual loops.
To combine the time complexities of consecutive loops, you need to consider the number of iterations performed by each loop and the amount of work performed in each iteration. The total time complexity of the algorithm can be calculated by multiplying the number of iterations of each loop by the time complexity of each iteration and taking the maximum of all possible combinations.
For example, consider the following code:
for i in range(n):
for j in range(m):
# some constant time operation
Here, the outer loop performs n iterations, and the inner loop performs m iterations for each iteration of the outer loop. So, the total number of iterations performed by the inner loop is n * m, and the total time complexity is O(n * m).
In another example, consider the following code:
for i in range(n):
for j in range(i):
# some constant time operation
Here, the outer loop performs n iterations, and the inner loop performs i iterations for each iteration of the outer loop, where i is the current iteration count of the outer loop. The total number of iterations performed by the inner loop can be calculated by summing the number of iterations performed in each iteration of the outer loop, which is given by the formula sum(i) from i=1 to n, which is equal to n * (n + 1) / 2. Hence, the total time complex
C++
//Here c is any positive constant
for (int i = 1; i <= m; i += c) {
// some O(1) expressions
}
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
// Time complexity of above code is O(m) + O(n) which is O(m + n)
// If m == n, the time complexity becomes O(2n) which is O(n).
//This code is contributed by Kshitij
C
for (int i = 1; i <= m; i += c) {
// some O(1) expressions
}
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
// Time complexity of above code is O(m) + O(n) which is O(m + n)
// If m == n, the time complexity becomes O(2n) which is O(n).
Java
for (int i = 1; i <= m; i += c) {
// some O(1) expressions
}
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}
// Time complexity of above code is O(m) + O(n) which is O(m + n)
// If m == n, the time complexity becomes O(2n) which is O(n).
// This code is contributed by Utkarsh
C#
// Here c is any positive constant
for (int i = 1; i <= m; i += c)
{
// some O(1) expressions
}
for (int i = 1; i <= n; i += c)
{
// some O(1) expressions
}
// Time complexity of above code is O(m) + O(n) which is O(m + n)
// If m == n, the time complexity becomes O(2n) which is O(n).
JavaScript
for (var i = 1; i <= m; i += c) {
// some O(1) expressions
}
for (var i = 1; i <= n; i += c) {
// some O(1) expressions
}
// Time complexity of above code is O(m) + O(n) which is O(m + n)
// If m == n, the time complexity becomes O(2n) which is O(n).
Python3
for i in range(1, m+1, c):
# some O(1) expressions
for i in range(1, n+1, c):
# some O(1) expressions
# Time complexity of above code is O(m) + O(n) which is O(m + n)
# If m == n, the time complexity becomes O(2n) which is O(n).
How to calculate time complexity when there are many if, else statements inside loops?
As discussed here, the worst-case time complexity is the most useful among best, average and worst. Therefore we need to consider the worst case. We evaluate the situation when values in if-else conditions cause a maximum number of statements to be executed.
For example, consider the linear search function where we consider the case when an element is present at the end or not present at all.
When the code is too complex to consider all if-else cases, we can get an upper bound by ignoring if-else and other complex control statements.
How to calculate the time complexity of recursive functions?
The time complexity of a recursive function can be written as a mathematical recurrence relation. To calculate time complexity, we must know how to solve recurrences. We will soon be discussing recurrence-solving techniques as a separate post.
Algorithms Cheat Sheet:
Algorithm | Best Case | Average Case | Worst Case |
Selection Sort | O(n^2) | O(n^2) | O(n^2) |
Bubble Sort | O(n) | O(n^2) | O(n^2) |
Insertion Sort | O(n) | O(n^2) | O(n^2) |
Tree Sort | O(nlogn) | O(nlogn) | O(n^2) |
Radix Sort | O(dn) | O(dn) | O(dn) |
Merge Sort | O(nlogn) | O(nlogn) | O(nlogn) |
Heap Sort | O(nlogn) | O(nlogn) | O(nlogn) |
Quick Sort | O(nlogn) | O(nlogn) | O(n^2) |
Bucket Sort | O(n+k) | O(n+k) | O(n^2) |
Counting Sort | O(n+k) | O(n+k) | O(n+k) |
Quiz on Analysis of Algorithms
For more details, please refer: Design and Analysis of Algorithms.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem