close
The Wayback Machine - https://web.archive.org/web/20240930192743/https://www.geeksforgeeks.org/how-to-analyse-loops-for-complexity-analysis-of-algorithms/
Open In App

How to Analyse Loops for Complexity Analysis of Algorithms

Last Updated : 08 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

Logarithmic Time Complexity O(Log n):

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.



Previous Article
Next Article

Similar Reads

How to analyse Complexity of Recurrence Relation
The analysis of the complexity of a recurrence relation involves finding the asymptotic upper bound on the running time of a recursive algorithm. This is usually done by finding a closed-form expression for the number of operations performed by the algorithm as a function of the input size, and then determining the order of growth of the expression
7 min read
Asymptotic Notation and Analysis (Based on input size) in Complexity Analysis of Algorithms
Asymptotic Analysis is defined as the big idea that handles the above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don't measure the actual running time). We calculate, how the time (or space) taken by an algorithm increases with the input size. Asymptotic notation is
8 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Sample Practice Problems on Complexity Analysis of Algorithms
Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops. Problem 1: Find the complexity of the below recurrence: { 3T(n-1), if n>0,T(n) = { 1, otherwise Solution: Let us solve using substitution. T(n) = 3T(n-1) = 3(3T(n-2)) = 32T(n-2) = 33T(n-3) ... ... = 3nT(n-n) = 3nT(0) = 3n This clearly shows
15 min read
Types of Asymptotic Notations in Complexity Analysis of Algorithms
We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don't depend on machine-specific constants and don't require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathemat
8 min read
Time Complexity and Space Complexity
Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc
14 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Step Count Method for Time Complexity Analysis
What is Time Complexity? Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm. Time Complexity can be calculated by using Two types of methods. They are: Step Count MethodAsymptotic Notation. Here, we will discuss the Step Count Method. What is Step Count M
4 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate wh
15+ min read
Time and Space Complexity Analysis of Queue operations
What is Queue?Queue is a linear data structure that follows FIFO approach (First In First Out). One can imagine a queue as a line of people waiting in sequential order which starts from the beginning of the line. It is an ordered list in which insertions are done at one end which is known as the rear and deletions are done from the other end known
15+ min read
Time and Space Complexity Analysis of Prim's Algorithm
The time complexity of Prim's algorithm is O(V2) using an adjacency matrix and O((V +E) log V) using an adjacency list, where V is the number of vertices and E is the number of edges in the graph. The space complexity is O(V+E) for the priority queue and O(V2) for the adjacency matrix representation. The algorithm's time complexity depends on the d
3 min read
Time and Space Complexity Analysis of Kruskal Algorithm
Kruskal's algorithm is a popular algorithm for finding the Minimum Spanning Tree (MST) of a connected, undirected graph. The time complexity of Kruskal's algorithm is O(E log E), where E is the number of edges in the graph. The space complexity of Kruskal's algorithm is O(V + E), where V is the number of vertices and E is the number of edges in the
2 min read
Time and Space Complexity Analysis of Merge Sort
The Time Complexity of Merge Sort is O(n log n) in both the average and worst cases. The space complexity of Merge sort is O(n). AspectComplexityTime ComplexityO(n log n)Space ComplexityO(n)Time Complexity Analysis of Merge Sort:Consider the following terminologies: T(k) = time taken to sort k elementsM(k) = time taken to merge k elements So, it ca
2 min read
Time and Space Complexity Analysis of Quick Sort
The time complexity of Quick Sort is O(n log n) on average case, but can become O(n^2) in the worst-case. The space complexity of Quick Sort in the best case is O(log n), while in the worst-case scenario, it becomes O(n) due to unbalanced partitioning causing a skewed recursion tree that requires a call stack of size O(n). VariationTime ComplexityS
4 min read
Time and Space Complexity Analysis of Bubble Sort
The time complexity of Bubble Sort is O(n^2) in the worst-case scenario and the space complexity of Bubble sort is O(1). Bubble Sort only needs a constant amount of additional space during the sorting process. Complexity TypeComplexityTime ComplexityBest: O(n)Average: O(n^2)Worst: O(n^2)Space ComplexityWorst: O(1)Time Complexity Analysis of Bubble
3 min read
Time and Space Complexity Analysis of Binary Search Algorithm
Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. AspectComplexityTime ComplexityO(log n)Space ComplexityO(1)The time and space complexities of the binary search algorithm are mentioned below.
3 min read
Practice Questions on Time Complexity Analysis
Prerequisite: Analysis of Algorithms1. What is the time, and space complexity of the following code: [GFGTABS] CPP int a = 0, b = 0; for (i = 0; i < N; i++) { a = a + rand(); } for (j = 0; j < M; j++) { b = b + rand(); } Java int a = 0, b = 0; for (i = 0; i < N; i++) { a = a + Math.random(); } for (j = 0; j < M; j++) { b = b + Math.rand
8 min read
Prune-and-Search | A Complexity Analysis Overview
The word "prune" means to reduce something by removing things that are not necessary. So, Prune-and-Search is an excellent algorithmic paradigm for solving various optimization problems. This approach was first suggested by Nimrod Megiddo in 1983. This approach always consists of several iterations. At each iteration, it discards a fraction, say f,
8 min read
Constant & Linear Space Complexity in Algorithms
Being a programmer, you might have solved a lot of programming challenges. In programming space and time complexity matters a lot when we need to execute a program. Our algorithm should be efficient, and it should take less time. Whenever you're writing a solution to a program, some memory is required to complete, and it is important for our progra
5 min read
RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Algorithms Sample Questions | Set 3 | Time Order Analysis
Question 1: What is the asymptotic boundary of T(n)? [Tex] T(n) = \sum_{i=2}^{n} log_{i}n = log_{2}n + log_{3}n + \ldots + log_{n}n [/Tex] θ( n*log(n) ) θ( n2 ) θ( n ) θ( n*log2(n) ) θ( n2*log2(n) ) Answer: 3 Explanation: To find appropriate upper and lower boundaries, an approach which first comes to mind is to expand
10 min read
Analysis of Algorithms | Big - Θ (Big Theta) Notation
In the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big - Theta notations represented by a Greek letter (Θ). Definition: Let g and f be the function from the set of natural numbers to itself. The function f is said to be Θ(g), if there
6 min read
Randomized Algorithms | Set 1 (Introduction and Analysis)
What is a Randomized Algorithm? An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger's algorithm, we randomly pick an edge. How to analyse Randomize
6 min read
Design and Analysis of Algorithms
Design and Analysis of Algorithms is a fundamental aspect of computer science that involves creating efficient solutions to computational problems and evaluating their performance. DSA focuses on designing algorithms that effectively address specific challenges and analyzing their efficiency in terms of time and space complexity. Table of Content W
2 min read
Analysis of algorithms | little o and little omega notations
The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants, mainly because this analysis doesn’t require algorithms to be implemented and time taken by programs to be compared. We have already discussed Three main asymptotic notations. The following 2 more asymptotic not
4 min read
Asymptotic Analysis and comparison of sorting algorithms
It is a well established fact that merge sort runs faster than insertion sort. Using asymptotic analysis. we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2). It is obvious because merge sort uses a divide-and-conquer approach by recursively solving the problems where as insertion sort follows an incremental approach.
15+ min read
Analysis of Algorithms | Big-Omega Ω Notation
In the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big-Omega Notation represented by a Greek letter (Ω). Table of Content What is Big-Omega Ω Notation?Definition of Big-Omega Ω Notation?How to Determine Big-Omega Ω Notation?Example of
9 min read