Skip to main content

Command Palette

Search for a command to run...

How to Find Time Complexity of Any Code - Beginner Friendly Guide

Learn how to analyze your code’s performance step by step using simple logic and real examples.

Published
•11 min read•View as Markdown
How to Find Time Complexity of Any Code - Beginner Friendly Guide

Why Do We Need Time Complexity ?

Let’s understand this with a simple real-life coding example.

Imagine two developers, Ram and Bharat, are given the same programming problem.

  • Ram writes a solution in 112 lines of code

  • Bharat solves the same problem in just 23 lines of code

Now, let’s look at how their programs perform:

  • Ram’s code takes 10,000 milliseconds (10 seconds) to run

  • Bharat’s code takes only 1,000 milliseconds (1 second) to run

Even though both solutions produce the same output, their execution time is very different.

When we compare these two programs, Bharat’s execution time is almost negligible compared to Ram’s. In performance analysis, we are not interested in the best or fastest case, but in the worst-case scenario -because that tells us how the program behaves under heavy input or pressure.

This is exactly why we need Time Complexity.

Time Complexity helps us:

  • Compare different solutions independently of hardware

  • Focus on how a program scales with input size

  • Identify which solution will perform better for large inputs

  • Choose the most efficient algorithm, not just the shortest code

So, instead of saying:

“This code runs fast on my machine”

We can confidently say:

“This algorithm is efficient and scalable”

That’s the real power of Time Complexity.

🍉 Writing fewer lines of code does not guarantee better performance - efficient logic does.


🔍 Types of Analysis in Time Complexity

To understand the time complexity of an algorithm, we analyze its performance under different conditions.
There are three types of analysis used to measure time complexity:

  1. Best Case

  2. Average Case

  3. Worst Case

Each type tells us how an algorithm behaves for different kinds of inputs.

✅ Best Case Analysis - Ω (Omega) Notation

The best case represents the minimum time an algorithm takes to execute.

  • It occurs when the input is in the most favorable condition

  • It is denoted using Omega (Ω) notation

  • It shows the lower bound of an algorithm’s running time

Example : Searching for an element that appears at the first position in an array.

⚖️ Average Case Analysis - θ (Theta) Notation

The average case represents the expected time taken by an algorithm for a typical input.

  • It considers all possible inputs

  • It is denoted using Theta (θ) notation

  • It gives a more realistic performance estimate, but is often hard to calculate

Example: Searching for an element in an array where the element can appear at any position.

❌ Worst Case Analysis - O (Big-O) Notation

The worst case represents the maximum time an algorithm can take to run.

  • It occurs when the input is in the least favorable condition

  • It is denoted using Big-O (O) notation

  • It defines the upper bound of an algorithm’s running time

This is the most commonly used analysis because it guarantees performance even in the worst scenario.

🧠 Note:

In real-world programming and interviews, we mostly focus on Worst Case (Big-O) because it helps us design reliable and scalable algorithms.


Mathematical Expressions and Time Complexity (Quick Intuition)

To understand time complexity, it helps to recognize common mathematical growth patterns. When input size increases, we focus on how fast the function grows, not the exact values.

👉 While calculating time complexity, constants and smaller terms are ignored.

🕧 Constant Time - O(1)

Equation: y = 5

  • Value does not depend on input size x

  • Always takes the same amount of time

Approximation: O(1)

📈 Linear Time - O(n)

Equation: y = 2x + 5

  • Time increases directly with input size

  • Constants are ignored

Approximation: O(n)

🔲 Quadratic Time - O(n²)

Equation: y = 2x² + 3x − 5

  • The highest power is x²

  • Lower terms are ignored

Approximation: O(n²)

🧊 Cubic Time - O(n³)

Equation: y = 2x³ − 2x² + x + 2

  • Dominated by x³

  • Grows very fast for large inputs

Approximation: O(n³)

📉 Logarithmic Time - O(log n)

Equation: y = log(x) + 2

  • Input size reduces each step

  • Very efficient for large inputs

Approximation: O(log n)

🚀 Exponential Time - O(aⁿ )

Equation: y = 3ˣ + 4

  • Growth doubles or triples with each input

  • Extremely slow for large values

Approximation: O(3ⁿ )

🧠 Note :

While finding time complexity, always keep the term with the highest growth rate and ignore constants and smaller terms.


How to find Out Time Complexity of - Constant Time (O(1))

Let’s understand constant time complexity using a simple C++ example.

🧑‍💻 Code Example

int x = 5;
cout << x << endl;

if (x == 5)
    cout << x;
else
    cout << "Welcome";

🔍 Step-by-Step Time Analysis

Assume :

  • Each statement takes 1 unit of time to execute.

Now, let’s analyze the code by line :

  1. int x = 5; —> 1 unit of time

  2. cout << x << endl; —> 1 unit of time

  3. if - else condition —> 1 unit of time (only one branch executes)

👉 Total time taken = 1 + 1+ 1 = 3 units

📌 Final Conclusion

The total execution time is constant and does not depend on input size.
Even if the program runs on a larger machine or a smaller one, the number of operations remains the same.

So, we say the time complexity of this code is:

✅ O(1) — Constant Time Complexity


How to find Out Time Complexity of - Linear Time (O(n))

Let’s understand linear time complexity using a simple C++ example.

🧑‍💻 Code Example

int n = 5;
cout << n << endl;

for (int i = 1; i <= n; i++) {
    cout << i << " ";
}

🔍 Step-by-Step Time Analysis

Assumption :

  • Each statement takes 1 unit of time to execute.

Now, let’s analyze the code by line :

  1. int n = 5; —> 1 unit of time

  2. cout << n —> 1 unit of time

  3. First for Loop

for (int i = 1; i <= n; i++)
  • Runs from 1 to n

  • Executes n times

➕ Total Time Calculation

Total time = 1 + 1 + n 
           = n + 2

📌 Final Conclusion

  • Ignore the constants (+2)

  • Keep the dominant term

👉 Dominant term here is n

So, we say the time complexity of this code is:

✅ O(n) — Linear Time Complexity


How to find Out Time Complexity of - Quadratic Time (O(n²))

Let’s understand Quadratic time complexity using a simple C++ example.

🧑‍💻 Code Example

int n = 5;
cout << n << endl;

for (int i = 1; i <= n; i++) {
    cout << i << " ";
}

for (int i = 1; i <= n; i++) {
   for (int j = 1; j <= n; j++) {
    cout << j << " ";
    }
}

🔍 Step-by-Step Time Analysis

Assumption :

  • Each statement takes 1 unit of time to execute.

Now, let’s analyze the code by line :

  1. Constant Statements
  • int n = 5; —> 1 unit

  • cout << n; —> 1 unit

  1. First for Loop (Single Loop)
for (int i = 1; i <= n; i++)
  • Runs from 1 to n

  • Executes n times

➡️ Time Taken = n units

  1. Second for Loop (Nested Loop)

    Outer Loop

for (int i = 1; i <= n; i++)
  • Executes n times

Inner Loop

for (int j = 1; j <= n; j++)
  • Executes n times for each outer loop iteration

➡️ Total executions = n x n = n² times

So, the statement :

cout << j << " ";

runs n² times.

➕ Total Time Calculation

Total time = 1 + 1 + n + n * n  
           = n² + n + 2

📌 Final Conclusion

When calculating time complexity, we :

  • Ignore the constants (+2)

  • Ignore lower - order terms (n)

  • Keep the dominant term (n²)

👉 Dominant term here is n²

So, we say the time complexity of this code is:

✅ O(n²) — Quadratic Time Complexity


How to find Out Time Complexity of - Cubic Time (O(n³))

Let’s understand Cubic time complexity using a simple C++ example.

🧑‍💻 Code Example

int n = 5;
cout << n << endl;

for (int i = 1; i <= n; i++) {
   for (int j = 1; j <= n; j++) {
        for (int k = 1; k <= n; k++) {
            cout << k << " ";
        }
    }
}

🔍 Step-by-Step Time Analysis

Assumption :

  • Each statement takes 1 unit of time to execute.

Now, let’s analyze the code by line :

  1. Constant Statements
  • int n = 5; —> 1 unit

  • cout << n; —> 1 unit

  1. Triple Nested for Loop

    🔁 Outer Loop

for (int i = 1; i <= n; i++)
  • Executes n times

➡️ Total executions = n times

🔁 Middle Loop

for (int j = 1; j <= n; j++)
  • Executes n times for each outer loop iteration

➡️ Total executions so far = n x n = n² times

🔁 Inner Loop

for (int j = 1; j <= n; j++)
  • Executes n times for each middle loop iteration

➡️ Total executions = n x n x n = n³ times

So, the statement :

cout << j << " ";

runs n³ times.

➕ Total Time Calculation

Total time = 1 + 1 + n * n * n  
           = n³ + 2

📌 Final Conclusion

When calculating time complexity, we :

  • Ignore the constants (+2)

  • Keep the dominant term (n³)

👉 Dominant term here is n³

So, we say the time complexity of this code is:

✅ O(n³) - Cubic Time Complexity


How to find Out Time Complexity of - Exponential Time (O(aⁿ))

Let’s understand Exponential time complexity using a simple C++ example.

🧑‍💻 Code Example

int fibonacci(int n) {
    if (n <= 1)
        return n;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

🔍 Step-by-Step Time Analysis

Assumption :

  • Each function call takes 1 unit of time .

1️⃣ BASE Case

if (n <= 1)
    return n;
  • Executes in constant time

  • Stops the recursion

2️⃣ RECURSIVE Calls

fibonacci(n - 1) + fibonacci(n - 2);
  • Each function call makes two more recursive calls

  • This creates a binary recursion tree

  • Number of calls grows rapidly as n increases

Example for n=4;

f(4)
|---- f(3)
|     | -- f(2)
|     | -- f(1)
|---- f(2)
      | -- f(1)
  • Each level roughly double the number of calls

📈 Growth Pattern

  • Calls increases like:
2⁰, 2¹, 2², 2³, ...
  • total number of operations ≈ 2ⁿ

➕ Total Time Calculation

T(n) ≈ 2ⁿ

📌 Final Conclusion

When calculating time complexity, we :

  • Ignore constants (+2)

  • Focus on how fast the function grows

👉 Growth here is exponential

So, we say the time complexity of this code is:

✅ O(2ⁿ) - Exponential Time Complexity (more generally written as O(aⁿ))


Time Complexity Summary Table (Quick Reference)

Time ComplexityNameHow It GrowsExample
O(1)Constant TimeAlways take the same timeAccessing an array elements
O(log n)Logarithmic TimeInput size reduces each stepBinary Search
O(n)Linear TimeGrows directly with input sizeSingle Loop
O(n²)Quadratic TimeNested loopsBubble sort
O(n³)Cubic TimeTriple Nested Loops3D matrix traversal
O(2ⁿ)Exponential TimeDoubles every stepFibonacci

🧠 Note : O(1) < O(log n) < O( n) < O (n log n) < O (n²) < O (n³) < O (2ⁿ) < O (n!)


Summary

Time complexity is not about writing fewer lines of code or making the program look smart. It is about how efficiently your code runs as the input size grows. By understanding time complexity, you learn how to think like a problem solver instead of just a coder.

Concepts like O(1), O(n), O(n²), O(log n), and O(2ⁿ) help us predict how our program will behave when the input becomes large. In real-world applications and technical interviews, we mostly care about the worst-case performance, because it guarantees that our code will not break or slow down under pressure. Once you get comfortable identifying loops, nested loops, and recursive calls, finding time complexity becomes much easier.

Remember, always focus on the dominant term, ignore constants, and think about how the input is changing in each step. With regular practice, analyzing time complexity will become a natural part of your coding journey - and this skill will help you write faster, scalable, and more professional code.