ProgrammingHardTCS Digital · Infosys SP

What is the time complexity of the following pseudocode, as a function of n?

What is the time complexity of the following pseudocode, as a function of n?
for (each i from 1 to n)
    for (each j from 1 to n)
        if (i == j)
            for (each k from 1 to n)
                count = count + 1
            end for
        end if
    end for
end for
  1. A. O(n²)
  2. B. O(n³)
  3. C. O(n)
  4. D. O(n² log n)

Correct answer: A. O(n²)

The two outer loops make n² checks. The innermost loop runs only when i == j, i.e. n times in total, adding n × n = n² work. Total O(n²), not O(n³).

More Pseudocode and Code Tracing questions

Exams that ask this topic