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++;
  }
}

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).

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 3

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz