AI Features

Example: Time Complexity of an Algorithm With Nested Loops

In this lesson, we will learn how to compute the time complexity of an algorithm that involves nested for loops.

A Program With Nested for Loops

Consider the following javascript program:

Node.js
//n can be anything
var n = 5
var m = 7
var sum = 0
for(var i = 0; i < n; i++)
for(var j = 0; j < m; j++)
sum += 1
console.log(sum)

It is a simple piece of code that prints the number of times the increment statement runs throughout the program. Let’s compute its time complexity.

Time Complexity

Let’s take the training wheels off and jump straight to line number 5. From the previous lesson, you would recall that it accounts for 6n+46n + 4 ...

Ask