Skip to main content

Command Palette

Search for a command to run...

Introduction of Time Complexity

Updated
2 min readView as Markdown

What is Time Complexity?

Time Complexity is a concept that helps us understand how much time a program or piece of code will take to run.

It shows us how the time taken by a program increases as the input size (like the amount of data) increases.


Real-Life Example:

Imagine you’re baking cookies.

  • If you bake 10 cookies, it might take you 30 minutes.

  • But if you bake 100 cookies, it will definitely take more time—maybe even 3 hours.

Just like this, as the amount of work (or data) increases, the time needed to finish it also increases.


Different Computers, Different Times:

Did you know? The same code can run at different speeds on different computers.

// Simple loop to illustrate time complexity
for (int i = 0; i < 1000000; i++) {
    // Some operation
}
  • On a fast computer, this might take 2 seconds to run.

  • On a slower computer, it might take 10 seconds.

But no matter what computer you use, the relationship between input size and time stays the same!


Why It Matters:

Understanding Time Complexity helps you predict how your program will behave as the input size grows.

Example:

 // Counting numbers up to n
for (int i = 1; i <= n; i++) {
    System.out.println(i);
}
  • For n = 10, it runs quickly.

  • For n = 1000, it takes longer.

This means you can choose or design better algorithms that don’t slow down too much as the input increases.


Simple Example:

Counting Numbers:

// Counting up to 10
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

// Counting up to 1000
for (int i = 1; i <= 1000; i++) {
    System.out.println(i);
}
  • If you have to count to 10, it’s quick.

  • If you have to count to 1,000, it takes longer.

Time complexity helps us understand this difference and prepares us for larger tasks.


Key Takeaway:

Time Complexity shows us the relationship between the size of the task and the time it takes to complete it.

Remember:

// An efficient algorithm
for (int i = 0; i < n; i += 2) {
    System.out.println(i);
}

Always aim to write code that works efficiently, even as the task gets bigger.

More from this blog

Amit singh's blog

235 posts