Why complexity matters?

Why complexity matters?

·

2 min read

Introduction

Big O simply means that as the input grows the runtime of an algorithm grows too. It's the way of describing relation between the input of the function as it grows how it affects the runtime of that function.

Relation between input size and processing time!

Types

  • f(n)=n

    as the input increases the runtime increases too

  • f(n)=n²

    as the input increases the runtime is squared

  • f(n)=1

    as the input increases it won't affect the runtime and it will be always constant

Examples

  • Sum of natural numbers
let sum = (num)=>{
let total = 0;
for(i = 0; i < num; i++){
total+=i;
}
return total;

Input

sum(5)

output

15

In the above example if the input is 5 then it will loop 5 times the total in loop will be assigned 5 times what if the input in 10million then it will loop 10 million times and total will be assigned 10 million times! so in short as the input will grow the time will grow too.

The complexity of the above example will be O(n)

  • Sum of natural numbers (different approach)
let sum = (num) =>{
return num * (num +1) /2;
}

Input

sum(5)

output

15

In the above example it really doesn't matter what the input number is, it can be either 5 or 5 billion! there will be only three operations that is multiplication followed by addition and division.

Conclusion

So the above 2 examples shows us why complexity is really important in real world problems so yes complexity matters!

If you have any suggestions or feedback please do reach me out on twitter or on linked.