Algorithms and Data Structures · Junior · Question 3 of 75
What is the time complexity of two nested loops over the same array of length n?
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
count++;
}
}- 1O(n)
- 2O(2n)
- ✓Correct answer: O(n²)
Explanation
For each of the n iterations of the outer loop the inner loop runs n times, so the body runs n × n times. O(2n) would be two loops one after another, and that simplifies to O(n).