Search⌘ K
AI Features

Example: Time Complexity of an Algorithm With Nested Loops

Explore how to determine the time complexity of algorithms containing nested loops by counting primitive operations and applying asymptotic analysis. Understand step-by-step how each loop contributes to overall complexity and learn to generalize these calculations for coding interview problems.

Now, we’ll analyze an algorithm with nested for loops.

A program with nested for loops

Consider the following Java program:

Java
class NestedLoop {
public static void main(String[] args) {
int n = 5; // 1 step
int m = 7; // 1 step
int sum = 0; // 1 step
for (int i = 0; i < n; i++) { // n steps
for (int j = 0; j < m; j++) { // n*m steps
sum++; // n*m steps
}
}
System.out.println("Sum: " + sum); // 1 step
}
}

It ...