Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Go Premium
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Analysis of Algorithms
Next article icon

Complete Guide On Complexity Analysis - Data Structure and Algorithms Tutorial

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Complexity analysis is defined as a technique to characterise the time taken by an algorithm with respect to input size (independent from the machine, language and compiler). It is used for evaluating the variations of execution time on different algorithms.

What is the need for Complexity Analysis?

  • Complexity Analysis determines the amount of time and space resources required to execute it.
  • It is used for comparing different algorithms on different input sizes.
  • Complexity helps to determine the difficulty of a problem.
  • often measured by how much time and space (memory) it takes to solve a particular problem
Complete Guide On Complexity Analysis
Complete Guide On Complexity Analysis

Things to learn about Complexity Analysis

  • What is Complexity Analysis?
  • What is the need for Complexity Analysis?
  • Asymptotic Notations
  • How to measure complexity?
    • 1. Time Complexity
    • 2. Space Complexity
    • 3. Auxiliary Space
  • How does Complexity affect any algorithm?
    • How to optimize the time and space complexity of an Algorithm?
  • Different types of Complexity exist in the program:
    • 1. Constant Complexity
    • 2. Logarithmic Complexity
    • 3. Linear Complexity
    • 4. Quadratic Complexity
    • 5. Factorial Complexity
    • 6. Exponential Complexity
  • Worst Case time complexity of different data structures for different operations
  • Complexity Analysis Of Popular Algorithms
  • Practice some questions on Complexity Analysis
  • practice with giving Quiz
  • Conclusion

Asymptotic Notations in Complexity Analysis:

1. Big O Notation

Big-O notation represents the upper bound of the running time of an algorithm. Therefore, it gives the worst-case complexity of an algorithm. By using big O- notation, we can asymptotically limit the expansion of a running time to a range of constant factors above and below. It is a model for quantifying algorithm performance. 
 

Graphical Representation

Mathematical Representation of Big-O Notation:

O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ f(n) ≤ cg(n) for all n ≥ n0 }

2. Omega Notation

Omega notation represents the lower bound of the running time of an algorithm. Thus, it provides the best-case complexity of an algorithm.
The execution time serves as a lower bound on the algorithm’s time complexity. It is defined as the condition that allows an algorithm to complete statement execution in the shortest amount of time.

Graphical Representation

Mathematical Representation of Omega notation :

Ω(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ cg(n) ≤ f(n) for all n ≥ n0 }
Note: Ω (g) is a set

3. Theta Notation

Theta notation encloses the function from above and below. Since it represents the upper and the lower bound of the running time of an algorithm, it is used for analyzing the average-case complexity of an algorithm. The execution time serves as both a lower and upper bound on the algorithm’s time complexity. It exists as both, the most, and least boundaries for a given input value.

Graphical Representation

Mathematical Representation:

Θ (g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 ≤ c1 * g(n) ≤ f(n) ≤ c2 * g(n) for all n ≥ n0}

4. Little ο asymptotic notation

Big-Ο is used as a tight upper bound on the growth of an algorithm’s effort (this effort is described by the function f(n)), even though, as written, it can also be a loose upper bound. “Little-ο” (ο()) notation is used to describe an upper bound that cannot be tight. 
 

Graphical Representation

Mathematical Representation:

f(n) = o(g(n)) means lim  f(n)/g(n) = 0 n→∞ 

5. Little ω asymptotic notation

Let f(n) and g(n) be functions that map positive integers to positive real numbers. We say that f(n) is ω(g(n)) (or f(n) ∈ ω(g(n))) if for any real constant c > 0, there exists an integer constant n0 ≥ 1 such that f(n) > c * g(n) ≥ 0 for every integer n ≥ n0. 

Mathematical Representation:

if f(n) ∈ ω(g(n)) then, 

lim  f(n)/g(n) = ∞ 

n→∞ 

Note:  In most of the Algorithm we use Big-O notation, as it is worst case Complexity Analysis.

How to measure complexity?

The complexity of an algorithm can be measured in three ways:

1. Time Complexity

The time complexity of an algorithm is defined as the amount of time taken by an algorithm to run as a function of the length of the input. Note that the time to run is a function of the length of the input and not the actual execution time of the machine on which the algorithm is running on

How is Time complexity computed?

To estimate the time complexity, we need to consider the cost of each fundamental instruction and the number of times the instruction is executed.

  • If we have statements with basic operations like comparisons, return statements, assignments, and reading a variable. We can assume they take constant time each O(1).
Statement 1: int a=5;            // reading a variable
statement 2; if( a==5) return true; // return statement
statement 3; int x= 4>5 ? 1:0; // comparison
statement 4; bool flag=true; // Assignment

This is the result of calculating the overall time complexity.

total time = time(statement1) + time(statement2) + ... time (statementN)

Assuming that n is the size of the input, let's use T(n) to represent the overall time and t to represent the amount of time that a statement or collection of statements takes to execute.

T(n) = t(statement1) + t(statement2) + ... + t(statementN); 

Overall, T(n)= O(1), which means constant complexity.

  • For any loop, we find out the runtime of the block inside them and multiply it by the number of times the program will repeat the loop.

for (int i = 0; i < n; i++) {
   cout << "GeeksForGeeks" << endl;
}

For the above example, the loop will execute n times, and it will print "GeeksForGeeks" N number of times. so the time taken to run this program is:

T(N)= n *( t(cout statement))
= n * O(1)
=O(n), Linear complexity.
  • For 2D arrays, we would have nested loop concepts, which means a loop inside a loop.

for (int i = 0; i < n; i++) {
   for (int j = 0; j < m; j++) {
       cout << "GeeksForGeeks" << endl;
   }
}

For the above example, the cout statement will execute n*m times, and it will print "GeeksForGeeks" N*M number of times. so the time taken to run this program is:

T(N)= n * m *(t(cout statement))
= n * m * O(1)
=O(n*m), Quadratic Complexity.

2. Space Complexity :

The amount of memory required by the algorithm to solve a given problem is called the space complexity of the algorithm. Problem-solving using a computer requires memory to hold temporary data or final result while the program is in execution. 

How is space complexity computed?

The space Complexity of an algorithm is the total space taken by the algorithm with respect to the input size. Space complexity includes both Auxiliary space and space used by input. 
Space complexity is a parallel concept to time complexity. If we need to create an array of size n, this will require O(n) space. If we create a two-dimensional array of size n*n, this will require O(n2) space.

In recursive calls stack space also counts.

Example:

int add (int n){
if (n <= 0){
return 0;
}
return n + add (n-1);
}
Here each call add a level to the stack :
1. add(4)
2. -> add(3)
3. -> add(2)
4. -> add(1)
5. -> add(0)
Each of these calls is added to call stack and takes up actual memory.
So it takes O(n) space.

However, just because you have n calls total doesn’t mean it takes O(n) space.

Look at the below function :

int addSequence (int n){
int sum = 0;
for (int i = 0; i < n; i++){
sum += pairSum(i, i+1);
}
return sum;
}
int pairSum(int x, int y){
return x + y;
}
There will be roughly O(n) calls to pairSum. However, those
calls do not exist simultaneously on the call stack,
so you only need O(1) space.

3. Auxiliary Space :

The temporary space needed for the use of an algorithm is referred to as auxiliary space. Like temporary arrays, pointers, etc. 
It is preferable to make use of Auxiliary Space when comparing things like sorting algorithms. 
for example, sorting algorithms take O(n) space, as there is an input array to sort. but auxiliary space is O(1) in that case. 

How does Complexity affect any algorithm?

Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of length of the input. While, the space complexity of an algorithm quantifies the amount of space or memory taken by an algorithm to run  as a function of the length of the input.

How to optimize the time and space complexity of an Algorithm?

Optimization means modifying the brute-force approach to a problem. It is done to derive the best possible solution to solve the problem so that it will take less time and space complexity. We can optimize a program by either limiting the search space at each step or occupying less search space from the start.

We can optimize a solution using both time and space optimization. To optimize a program,

  1. We can reduce the time taken to run the program and increase the space occupied;
  2. we can reduce the memory usage of the program and increase its total run time, or
  3. we can reduce both time and space complexity by deploying relevant algorithms

Different types of Complexity exist in the program:

1. Constant Complexity

If the function or method of the program takes negligible execution time. Then that will be considered as constant complexity. 

Example:  The below program takes a constant amount of time.

C++
// C program for the above approach
#include <stdio.h>

// Function to check if a
// number is even or odd
void checkEvenOdd(int N)
{
    // Find remainder
    int r = N % 2;

    // Condition for even
    if (r == 0) {
        printf("Even");
    }

    // Otherwise
    else {
        printf("Odd");
    }
}

// Driver Code
int main()
{
    // Given number N
    int N = 101;

    // Function Call
    checkEvenOdd(N);

    return 0;
}
Java
// Java program for the above approach

public class GFG {
    // Function to check if a number is even or odd
    public static void checkEvenOdd(int N)
    {
        // Find remainder
        int r = N % 2;

        // Condition for even
        if (r == 0) {
            System.out.println("Even");
        }
        // Otherwise
        else {
            System.out.println("Odd");
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        // Given number N
        int N = 101;

        // Function call
        checkEvenOdd(N);
    }
}
Python3
# Python3 program for the above approach

# Function to check if a
# number is even or odd


def checkEvenOdd(N):
    # Find remainder
    r = N % 2
    # Condition for even
    if (r == 0):
        print("Even")
    # Otherwise
    else:
        print("Odd")


# Driver Code
if __name__ == '__main__':
    # Given number N
    N = 101
    # Function Call
    checkEvenOdd(N)
C#
// C# program for the above approach

using System;

public class GFG {

    // Function to check if a number is even or odd
    static void CheckEvenOdd(int N)
    {
        // Find remainder
        int r = N % 2;

        // Condition for even
        if (r == 0) {
            Console.WriteLine("Even");
        }
        // Otherwise
        else {
            Console.WriteLine("Odd");
        }
    }

    static public void Main()
    {

        // Code
        // Given number N
        int N = 101;

        // Function call
        CheckEvenOdd(N);
    }
}
JavaScript
// JavaScript program for the above approach

// Function to check if a 
// number is even or odd
function checkEvenOdd(N) {

    // Find remainder
    let r = N % 2;

    // Condition for even
    if (r == 0) {
        console.log("Even");
    }

    // Otherwise
    else {
        console.log("Odd");
    }
}

// Driver code

// Given number N
let N = 101;

// Function call
checkEvenOdd(N);

Output
Odd
Constant  Complexity Graph

2. Logarithmic Complexity:

It imposes a complexity of O(log(N)). It undergoes the execution of the order of log(N) steps. To perform operations on N elements, it often takes the logarithmic base as 2. 

Example: The below program takes logarithmic complexity.

C++
// C++ program to implement recursive Binary Search
#include <bits/stdc++.h>
using namespace std;

// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r >= l) {
        int mid = l + (r - l) / 2;

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, r, x);
    }

    // We reach here when element is not
    // present in array
    return -1;
}

int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
    return 0;
}
Java
// Java program to implement recursive Binary Search

class BinarySearch {
    // A recursive binary search function. It returns
    // the index of x in the given array arr[l..r] if present,
    // otherwise returns -1
    static int binarySearch(int arr[], int l, int r, int x) {
        if (r >= l) {
            int mid = l + (r - l) / 2;

            // If the element is present at the middle itself
            if (arr[mid] == x)
                return mid;

            // If element is smaller than mid, then
            // it can only be present in the left subarray
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);

            // Else the element can only be present
            // in the right subarray
            return binarySearch(arr, mid + 1, r, x);
        }

        // We reach here when the element is not present in the array
        return -1;
    }

    public static void main(String args[]) {
        int arr[] = {2, 3, 4, 10, 40};
        int x = 10;
        int n = arr.length;
        int result = binarySearch(arr, 0, n - 1, x);
        if (result == -1)
            System.out.println("Element is not present in the array");
        else
            System.out.println("Element is present at index " + result);
    }
}

// This code is contributed by Utkarsh Kumar
Python3
# Python program for the above approach

# A recursive binary search function. It returns
# location of x in the given array arr[l..r] if present,
# otherwise returns -1
def binarySearch(arr, l, r, x):
    if r >= l:
        mid = l + (r - l) // 2

        # If the element is present at the middle itself
        if arr[mid] == x:
            return mid

        # If the element is smaller than mid, then
        # it can only be present in the left subarray
        elif arr[mid] > x:
            return binarySearch(arr, l, mid - 1, x)

        # Else the element can only be present
        # in the right subarray
        else:
            return binarySearch(arr, mid + 1, r, x)

    # We reach here when the element is not
    # present in the array
    return -1

# Driver code
arr = [2, 3, 4, 10, 40]
x = 10

# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)

# Print the result
if result == -1:
    print("Element is not present in array")
else:
    print(f"Element is present at index {result}")

# This code is contributed by Susobhan Akhuli
C#
// C# program for the above approach
using System;

public class GFG {
    // A recursive binary search function. It returns
    // location of x in given array arr[l..r] if present,
    // otherwise returns -1
    static int BinarySearch(int[] arr, int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;

            // If the element is present at the middle
            // itself
            if (arr[mid] == x)
                return mid;

            // If the element is smaller than mid, then
            // it can only be present in the left subarray
            if (arr[mid] > x)
                return BinarySearch(arr, l, mid - 1, x);

            // Else the element can only be present
            // in the right subarray
            return BinarySearch(arr, mid + 1, r, x);
        }

        // We reach here when the element is not
        // present in the array
        return -1;
    }

    static void Main()
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;
        int n = arr.Length;
        int result = BinarySearch(arr, 0, n - 1, x);
        Console.WriteLine(
            (result == -1)
                ? "Element is not present in array"
                : $"Element is present at index {result}");
    }
}

// This code is contributed by Susobhan Akhuli
JavaScript
// A recursive binary search function. It returns
// the index of x in the given array arr[l..r] if present,
// otherwise returns -1
function binarySearch(arr, l, r, x) {
    if (r >= l) {
        let mid = l + Math.floor((r - l) / 2);

        // If the element is present at the middle itself
        if (arr[mid] === x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in the left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);

        // Else the element can only be present
        // in the right subarray
        return binarySearch(arr, mid + 1, r, x);
    }

    // We reach here when the element is not present in the array
    return -1;
}

// Main function
function main() {
    const arr = [2, 3, 4, 10, 40];
    const x = 10;
    const n = arr.length;
    const result = binarySearch(arr, 0, n - 1, x);
    if (result === -1)
        console.log("Element is not present in the array");
    else
        console.log("Element is present at index " + result);
}

// Call the main function
main();

Output
Element is present at index 3
Logarithmic Complexity Graph

3. Linear Complexity:

It imposes a complexity of O(N). It encompasses the same number of steps as that of the total number of elements to implement an operation on N elements.

Example: The below program takes Linear complexity.

C++
// C++ code to linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1

#include <iostream>
using namespace std;

int search(int arr[], int N, int x)
{
    int i;
    for (i = 0; i < N; i++)
        if (arr[i] == x)
            return i;
    return -1;
}

// Driver's code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    int result = search(arr, N, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
    return 0;
}
Java
// Java code to linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1
class GFG {
    static int search(int[] arr, int N, int x)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == x) {
                return i;
            }
        }
        return -1;
    }

    // Driver's code
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;
        int N = arr.length;

        // Function call
        int result = search(arr, N, x);
        if (result == -1) {
            System.out.println(
                "Element is not present in array");
        }
        else {
            System.out.println(
                "Element is present at index " + result);
        }
    }
}
// This code is contributed by prasad264
Python3
# Python code to linearly search x in arr[]. If x
# is present then return its location, otherwise
# return -1
def search(arr, x):
    for i in range(len(arr)):
        if arr[i] == x:
            return i
    return -1

# Driver's code
if __name__ == "__main__":
    arr = [2, 3, 4, 10, 40]
    x = 10

    # Function call
    result = search(arr, x)

    if result == -1:
        print("Element is not present in array")
    else:
        print(f"Element is present at index {result}")

# This code is contributed by Susobhan Akhuli
C#
using System;

public class GFG {
    // Function to linearly search x in arr[]. If x
    // is present, then return its location; otherwise,
    // return -1.
    static int Search(int[] arr, int N, int x)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }

    static public void Main()
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;
        int N = arr.Length;

        // Function call
        int result = Search(arr, N, x);
        if (result == -1)
            Console.WriteLine(
                "Element is not present in the array.");
        else
            Console.WriteLine("Element is present at index "
                              + result);
    }
}
JavaScript
// Function to linearly search x in arr[]. If x is present then return its location, otherwise return -1
function search(arr, x) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === x) {
            return i;
        }
    }
    return -1;
}

// Driver's code
function main() {
    const arr = [2, 3, 4, 10, 40];
    const x = 10;

    // Function call
    const result = search(arr, x);
    if (result === -1) {
        console.log("Element is not present in array");
    } else {
        console.log("Element is present at index " + result);
    }
}

// Call the main function
main();

Output
Element is present at index 3
Linear Complexity Graph

4. Quadratic Complexity: 

It imposes a complexity of O(n2). For N input data size, it undergoes the order of N2 count of operations on N number of elements for solving a given problem.

Example: The below program takes quadratic complexity.

C++
// C++ program for the above approach
#include <bits/stdc++.h>

using namespace std;

// Function to find and print pair
bool chkPair(int A[], int size, int x)
{
    for (int i = 0; i < (size - 1); i++) {
        for (int j = (i + 1); j < size; j++) {
            if (A[i] + A[j] == x) {
                return 1;
            }
        }
    }

    return 0;
}

// Driver code
int main()
{
    int A[] = { 0, -1, 2, -3, 1 };
    int x = -2;
    int size = sizeof(A) / sizeof(A[0]);

    if (chkPair(A, size, x)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << x << endl;
    }

    return 0;
}

// This code is contributed by Samim Hossain Mondal.
Java
// Java program for the above approach
import java.util.*;

public class GFG {
    // Function to find and print pair
    static boolean chkPair(int[] A, int x)
    {
        int size = A.length;
        for (int i = 0; i < size - 1; i++) {
            for (int j = i + 1; j < size; j++) {
                if (A[i] + A[j] == x) {
                    return true;
                }
            }
        }
        return false;
    }

    // Driver code
    public static void main(String[] args)
    {
        int[] A = { 0, -1, 2, -3, 1 };
        int x = -2;

        if (chkPair(A, x)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No " + x);
        }
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Python program for the above approach

# Function to find and print pair
def chkPair(A, x):
    size = len(A)
    for i in range(size - 1):
        for j in range(i + 1, size):
            if A[i] + A[j] == x:
                return True
    return False

# Driver code
if __name__ == "__main__":
    A = [0, -1, 2, -3, 1]
    x = -2

    if chkPair(A, x):
        print("Yes")
    else:
        print("No", x)

# This code is contributed by Susobhan Akhuli
JavaScript
// Function to find and print pair
function chkPair(A, x) {
    var size = A.length;
    for (var i = 0; i < size - 1; i++) {
        for (var j = i + 1; j < size; j++) {
            if (A[i] + A[j] === x) {
                return true;
            }
        }
    }
    return false;
}

// Driver code
var A = [0, -1, 2, -3, 1];
var x = -2;

if (chkPair(A, x)) {
    console.log("Yes");
} else {
    console.log("No", x);
}

Output
Yes
Quadratic Complexity Graph

5. Factorial Complexity: 

It imposes a complexity of O(n!). For N input data size, it executes the order of N! steps on N elements to solve a given problem.

Example: The below program takes factorial complexity.

C++
// C++ program to print all
// permutations with duplicates allowed
#include <bits/stdc++.h>
using namespace std;

// Function to print permutations of string
// This function takes three parameters:
// 1. String
// 2. Starting index of the string
// 3. Ending index of the string.
void permute(string& a, int l, int r)
{
    // Base case
    if (l == r)
        cout << a << endl;
    else {
        // Permutations made
        for (int i = l; i <= r; i++) {

            // Swapping done
            swap(a[l], a[i]);

            // Recursion called
            permute(a, l + 1, r);

            // backtrack
            swap(a[l], a[i]);
        }
    }
}

// Driver Code
int main()
{
    string str = "ABC";
    int n = str.size();

    // Function call
    permute(str, 0, n - 1);
    return 0;
}

// This is code is contributed by rathbhupendra
Java
// Java program for the above approach
import java.util.*;

public class GFG {
    // Function to print permutations of string
    // This function takes three parameters:
    // 1. String
    // 2. Starting index of the string
    // 3. Ending index of the string.
    static void permute(char[] a, int l, int r)
    {
        // Base case
        if (l == r)
            System.out.println(new String(a));
        else {
            // Permutations made
            for (int i = l; i <= r; i++) {
                // Swapping done
                swap(a, l, i);

                // Recursion called
                permute(a, l + 1, r);

                // Backtrack
                swap(a, l, i);
            }
        }
    }

    // Function to swap characters at positions i and j in
    // the array
    static void swap(char[] arr, int i, int j)
    {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Driver Code
    public static void main(String[] args)
    {
        String str = "ABC";
        int n = str.length();
        char[] arr = str.toCharArray();

        // Function call
        permute(arr, 0, n - 1);
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Function to print permutations of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
def permute(a, l, r):
    # Base case
    if l == r:
        print("".join(a))
    else:
        # Permutations made
        for i in range(l, r + 1):
            # Swapping done
            a[l], a[i] = a[i], a[l]

            # Recursion called
            permute(a, l + 1, r)

            # backtrack
            a[l], a[i] = a[i], a[l]

# Driver Code
if __name__ == "__main__":
    str = list("ABC")
    n = len(str)

    # Function call
    permute(str, 0, n - 1)
#this code is contribuited by Utkarsh
JavaScript
// Function to print permutations of string
// This function takes three parameters:
// 1. String
// 2. Starting index of the string
// 3. Ending index of the string.
function permute(a, l, r) {
    // Base case
    if (l == r)
        console.log(a);
    else {
        // Permutations made
        for (let i = l; i <= r; i++) {

            // Swapping done
            a = swap(a, l, i);

            // Recursion called
            permute(a, l + 1, r);

            // backtrack
            a = swap(a, l, i);
        }
    }
}

// Utility function to swap characters at position i and j in a string
function swap(str, i, j) {
    const arr = str.split('');
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr.join('');
}

// Driver Code
let str = "ABC";
let n = str.length;

// Function call
permute(str, 0, n - 1);

Output
ABC
ACB
BAC
BCA
CBA
CAB
Factorial Complexity Graph

6. Exponential Complexity: 

It imposes a complexity of O(2N), O(N!), O(nk), …. For N elements, it will execute the order of the count of operations that is exponentially dependable on the input data size. 

Example: The below program takes exponential complexity.

C++
// A recursive solution for subset sum problem
#include <iostream>
using namespace std;

// Returns true if there is a subset
// of set[] with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{

    // Base Cases
    if (sum == 0)
        return true;
    if (n == 0)
        return false;

    // If last element is greater than sum,
    // then ignore it
    if (set[n - 1] > sum)
        return isSubsetSum(set, n - 1, sum);

    /* else, check if sum can be obtained by any
of the following:
    (a) including the last element
    (b) excluding the last element */
    return isSubsetSum(set, n - 1, sum)
        || isSubsetSum(set, n - 1, sum - set[n - 1]);
}

// Driver code
int main()
{
    int set[] = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    int n = sizeof(set) / sizeof(set[0]);
    if (isSubsetSum(set, n, sum) == true)
        cout <<"Found a subset with given sum";
    else
        cout <<"No subset with given sum";
    return 0;
}

// This code is contributed by shivanisinghss2110
Java
// Java program for the above approach
public class GFG {
    // Returns true if there is a subset
    // of set[] with sum equal to given sum
    static boolean isSubsetSum(int[] set, int n, int sum)
    {
        // Base Cases
        if (sum == 0)
            return true;
        if (n == 0)
            return false;

        // If last element is greater than sum,
        // then ignore it
        if (set[n - 1] > sum)
            return isSubsetSum(set, n - 1, sum);

        /* else, check if sum can be obtained by any
        of the following:
        (a) including the last element
        (b) excluding the last element */
        return isSubsetSum(set, n - 1, sum)
            || isSubsetSum(set, n - 1, sum - set[n - 1]);
    }

    // Driver code
    public static void main(String[] args)
    {
        int[] set = { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        int n = set.length;
        if (isSubsetSum(set, n, sum))
            System.out.println(
                "Found a subset with given sum");
        else
            System.out.println("No subset with given sum");
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Python program for the above approach

# Returns true if there is a subset
# of set[] with sum equal to given sum
def isSubsetSum(set, n, sum):
    # Base Cases
    if (sum == 0):
        return True
    if (n == 0):
        return False

    # If last element is greater than sum,
    # then ignore it
    if (set[n - 1] > sum):
        return isSubsetSum(set, n - 1, sum)

    # Check if sum can be obtained by
    # (a) including the last element
    # (b) excluding the last element
    return (isSubsetSum(set, n - 1, sum)
            or isSubsetSum(set, n - 1, sum - set[n - 1]))


# Driver code
if __name__ == "__main__":
    set = [3, 34, 4, 12, 5, 2]
    sum = 9
    n = len(set)
    if (isSubsetSum(set, n, sum)):
        print("Found a subset with given sum")
    else:
        print("No subset with given sum")
JavaScript
// Function to check if there is a subset of set[] with sum equal to given sum
function isSubsetSum(set, n, sum) {
    // Base Cases
    if (sum === 0)
        return true;
    if (n === 0)
        return false;

    // If last element is greater than sum, then ignore it
    if (set[n - 1] > sum)
        return isSubsetSum(set, n - 1, sum);

    /* else, check if sum can be obtained by either:
        (a) including the last element
        (b) excluding the last element */
    return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);
}

// Driver code
let set = [3, 34, 4, 12, 5, 2];
let sum = 9;
let n = set.length;
if (isSubsetSum(set, n, sum))
    console.log("Found a subset with given sum");
else
    console.log("No subset with given sum");

Output
Found a subset with given sum
Exponential Complexity Graph 

Worst Case time complexity of different data structures for different operations

Data structure

Access

Search

Insertion

Deletion

Array

O(1)

O(N)

O(N)

O(N)

Stack

O(N)

O(N)

O(1)

O(1)

Queue

O(N)

O(N)

O(1)

O(1)

Singly Linked list

O(N)

O(N)

O(N)

O(N)

Doubly Linked List

O(N)

O(N)

O(1)

O(1)

Hash Table

O(N)

O(N)

O(N)

O(N)

Binary Search Tree

O(N)

O(N)

O(N)

O(N)

AVL Tree

O(log N)

O(log N)

O(log N)

O(log N)

Binary Tree

O(N)

O(N)

O(N)

O(N)

Red Black Tree

O(log N)

O(log N)

O(log N)

O(log N)

Complexity Analysis Of Popular Algorithms:

Algorithm

Complexity

1.  Linear Search Algorithm

 O(N)

2  Binary Search

O(LogN)

3. Bubble Sort 

O(N^2) 

4. Insertion Sort

O(N^2) 

5. Selection Sort

O(N^2) 

6. QuickSort

O(N^2) worst

7  Merge Sort

O(N log(N))

8. Counting Sort

O(N)

9  Radix Sort

O((n+b) * logb(k)).

10. Sieve of Eratosthenes

O(n*log(log(n)))

11. KMP Algorithm

O(N)

12.  Z algorithm

O(M+N)

13.  Rabin-Karp Algorithm

O(N*M).

14. Johnson’s algorithm

O(V2log V + VE)

15.  Prim’s Algorithm

O(V2)

16 Kruskal’s Algorithm

O(ElogV)

17.  0/1 Knapsack 

O(N * W)

18. Floyd Warshall Algorithm

O(V3)

19. Breadth First Search

O(V+E)

20. Depth first Search

O(V + E)

Practice some questions on Complexity Analysis:

  • Practice Questions on Time Complexity Analysis
  • Miscellaneous Problems of Time Complexity
  • Sample Practice Problems on Complexity Analysis of Algorithm

Practice with giving  Quiz :

  • Top MCQs on Complexity Analysis of Algorithms with Answers
  • Top MCQs on NP-Complete Complexity with Answers
  • Top MCQs on Complexity Analysis using Recurrence Relations with Answers

Conclusion:

Complexity analysis is a very important technique to analyze any problem. The interviewer often checks your ideas and coding skills by asking you to write a code giving restrictions on its time or space complexities. By solving more and more problems anyone can improve their logical thinking day by day. Even in coding contests optimized solutions are accepted. The naive approach can give TLE(Time limit exceed).


Next Article
Analysis of Algorithms

P

pinkigfg
Improve
Article Tags :
  • Analysis of Algorithms
  • DSA
  • time complexity

Similar Reads

    Basics & Prerequisites

    Logic Building Problems
    Logic building is about creating clear, step-by-step methods to solve problems using simple rules and principles. It’s the heart of coding, enabling programmers to think, reason, and arrive at smart solutions just like we do.Here are some tips for improving your programming logic: Understand the pro
    2 min read
    Analysis of Algorithms
    Analysis of Algorithms is a fundamental aspect of computer science that involves evaluating performance of algorithms and programs. Efficiency is measured in terms of time and space.Basics on Analysis of Algorithms:Why is Analysis Important?Order of GrowthAsymptotic Analysis Worst, Average and Best
    1 min read

    Data Structures

    Array Data Structure
    In 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 Structure
    A 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 Structure
    Hashing 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 Structure
    A 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 Structure
    A 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 Structure
    A 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 Structure
    Tree 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 Structure
    Graph 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 Structure
    The 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 Algorithms
    Searching 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 Algorithms
    A 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 Recursion
    The 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 Algorithms
    Greedy 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 Algorithms
    Graph 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 DP
    Dynamic 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 Algorithms
    Bitwise 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 Tree
    Segment 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 Searching
    Pattern 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
    Geometry
    Geometry 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

    Interview Corner: All Resources To Crack Any Tech Interview
    This article serves as your one-stop guide to interview preparation, designed to help you succeed across different experience levels and company expectations. Here is what you should expect in a Tech Interview, please remember the following points:Tech Interview Preparation does not have any fixed s
    3 min read
    GfG160 - 160 Days of Problem Solving
    Are you preparing for technical interviews and would like to be well-structured to improve your problem-solving skills? Well, we have good news for you! GeeksforGeeks proudly presents GfG160, a 160-day coding challenge starting on 15th November 2024. In this event, we will provide daily coding probl
    3 min read

    Practice Problem

    GeeksforGeeks Practice - Leading Online Coding Platform
    GeeksforGeeks Practice is an online coding platform designed to help developers and students practice coding online and sharpen their programming skills with the following features. GfG 160: This consists of most popular interview problems organized topic wise and difficulty with with well written e
    6 min read
    Problem of The Day - Develop the Habit of Coding
    Do you find it difficult to develop a habit of Coding? If yes, then we have a most effective solution for you - all you geeks need to do is solve one programming problem each day without any break, and BOOM, the results will surprise you! Let us tell you how:Suppose you commit to improve yourself an
    5 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences