Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

Time Complexity

Go to Problems

Level 1

Jump to Level 2

Level 2

Jump to Level 3

Level 3

Jump to Level 4

Level 4

Jump to Level 5

Level 5

Jump to Level 6

Level 6

Jump to Level 7

Level 7

Jump to Level 8

Level 8

Be a Code Ninja!
Contents

Time Complexity Examples

Let us discuss some important examples of time complexity.

Example 1: The following is the program for finding the highest power less than 2. Find its Time complexity.

void f( int n )
{
    while( n != 0 )
    {
        n/=2;
    }
    
}
class DivideByTwo
{
    public static void f(int n)
    {
        while(n != 0)
        {
            n/=2;
        }
    }
} 
def f(n)
{
    while n != 0 :
        n/=2
    
}

Time Complexity: The time complexity of the above program is O(log2n) . This is because at every step we divide n by 2 .

Example 2: The following is the program for finding all the subsets of a given set. Find its Time complexity.

void find_subsets( int arr[] , int n )
{
    for ( int i=0 ; i < pow(2,n) ; i++)
    {
        
        for(int j=0 ; j < n ; j++)
        {
            if((i&(1<
		
class Subsets
{
    public static void find_subsets( int arr[] , int n )
    {
        for ( int i=0 ; i < pow(2,n) ; i++)
        {
            
            for(int j=0 ; j < n ; j++)
            {
                if((i&(1<
		
def find_subsets( arr , n )

    for i in range(0,1<
		

Time Complexity: As can be seen , the outer loop runs O(2^n) times, and the inner loop runs O(n) times. 

Therefore the total time complexity is the multiplication of both i.e. O(2^n * n).

Example 3: Let’s take the example of a fibonacci number. The following program finds the nth fibonacci number. What is its time complexity?

int fib (int n)
{
    if(n <= 1) 
    {
        return 1;
    }
    return fib(n-1) + fib(n-2);
}
class Fibonacci
{
    public static int fib (int n)
    {
        if(n<=1)
        {
            return n;
        }
        else
        {
            return fib(n-1)+fib(n-2);
        }
    }   
}
def fib (n)
{
    if n <= 1:
        return 1;
    return fib(n-1) + fib(n-2);
}

The derivation of the time complexity is slightly non trivial , so you can skip it if you want.

The characteristic equation of the equation ( F(n) = F(n-1) + F(n-2) ) would be x^2 - x -1 =0

Solving the above equation we would get 2 roots.

x= ( 1 + 5 )/2 and x= ( 1 - 5 )/2

As we know the solution of a linear recursive function is given as

F(n) = (1n + 2n )

Using the above fact

  • F(n) = ( ( 1 + 5 )/2 ) ^n + ( ( 1 - 5 )/2 ) ^n
  • T(n) = O ( ( ( 1 + 5 )/2 ) ^n) + O( ( ( 1 - 5 )/2 ) ^n)
  • T(n) = O ( ( ( 1 + 5 )/2 ) ^n)
  • T(n) = O ( 1.6180 ) ^n

But is this the best time complexity we can achieve? No , of course not. We can simply use dynamic programming to memoize the above program and bring down the complexity to linear.

int dp[1000];

int fib (int n)
{
    if(n <= 1) 
    {
        return 1;
    }
    if(dp[n] != -1)
    {
        return dp[n];    
    }
    return dp[n] = fib(n-1) + fib(n-2);
}
class Fibonacci
{
    int[] dp = new int[1000];
    public static int fib (int n)
    {
        if(n<=1)
        {
            return n;
        }
        if(dp[n] != 0)
        {
            return dp[n];
        }
        dp[n] = fib(n-1) + fib(n-2);
    }   
}
dp=[0,1]

def fib (int n)
{
    if n < len(dp):
        return dp[n]
    else :
        dp.append(fib(n-1)+fib(n-2))
        return dp[n] 
}

The time complexity of the above program would be linear i.e. O(n).

As there are only ‘n’ distinct states.

We can further reduce the time complexity to O(logn) by using ‘Matrix Exponentiation’.

Example 4: This is a very commonly asked question in the interview. What is the time complexity of the below program?

for( int i = 1 ; i <= n ; i++)
    {
        for( int j = i ; j <= n ; j+=i)
        {
            cout<<"hello";
        }
    }
for( int i = 1 ; i <= n ; i++)
    {
        for( int j = i ; j <= n ; j+=i)
        {
              System.out.println(i);
        }
    }
for i in range(1,n):
    for j in range(i,n,i):
        print("hello")

Even though the time complexity of the above algorithm appears to be O(n*n) , in reality it is actually O (nlogn). You can try to derive it by yourself.

The same principle is used in many famous algorithms like sieve. 

Serious about Learning Programming ?

Learn this and a lot more with Scaler Academy's industry vetted curriculum which covers Data Structures & Algorithms in depth.

This topic has only Multiple Choice Questions

Jump to subsequent topics to solve code problems.

Time Complexity Problems

Basic primer
Problem Score Companies Time Status
LOOP_CMPL 20 2:43
NESTED_CMPL 20
1:10
NESTED_CMPL2 30
1:25
CHOOSE4 50
0:57
Math
Problem Score Companies Time Status
WHILE_CMPL 50
1:31
NESTED_CMPL3 80 3:56
LOOP_CMPL2 80
2:43
GCD_CMPL 150
4:13
Compare functions
Problem Score Companies Time Status
CHOOSE3 50
1:39
CHOOSE1 50
1:43
CHOOSE2 80
2:23
Function calling itself
Problem Score Companies Time Status
REC_CMPL1 80 6:58
REC_CMPL2 80
6:25
REC_CMPL3 150
4:39
Amortized complexity
Problem Score Companies Time Status
AMORTIZED1 100
3:03
Excel at your interview with Masterclasses Know More
Certificate included
What will you Learn?
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test