Big O notation in simple terms – July 2020

I’ve been trying to learn more about BigO notation this month (July 2020). So far I have learned about BigO notation when it comes to time complexity and space complexity. If you have a function like:

function stringPrinter(str1) {
console.log(str1)
}

$ stringPrinter("Boop")
Boop

The time complexity is O(1) in BigO notation and the space complexity is also O(1). As it has a fixed amount of time ‘(1)’ it will take to complete as it really doesn’t matter how long ‘str1’ gets. Variable assignments aren’t factored into time. The space this function will take up is also constant since nothing is being iterated over or built after the log entry is made.

However if you have a function like below:

function stringLooper(str1) {
   for (i in str1) { 
      console.log(str1[i])
   }
}
$ stringLooper("Boop")
B
o
o
p

This has a time complexity of O(n) and space complexity of O(n) in BigO notation. This is due to the fact that as your input string variable, ‘str1’ grows, the number of times the loop runs grows with the input string length.

If you make nested for loops, you are doubling your time and space complexity: O(n²), <=== very bad.  The more you nest, the worse it becomes.

A nice simple image for reference, credits to: https://danielmiessler.com/study/big-o-notation/

Leave a Reply

You are currently viewing Big O notation in simple terms – July 2020