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- A. O(n²)
- B. O(n³)
- C. O(n)
- 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³).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Strings are immutable here, so s = s + "a" copies the whole current string. What is the time complexity of the following pseudocode, as a…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Boolean prime[2..50] //…
- What will be the output of the following pseudocode? Integer count = 0, n = 2, s = 0 while (count < 10) Boolean pr = true for (each d from…
- What will be the output of the following pseudocode? (XOR is true when exactly one side is true; NOT binds tighter than AND, which binds…
- What will be the output of the following pseudocode? Integer a[6] = {3, 8, 1, 9, 4, 7} Integer best = -1, i = 0, j = 5 while (i < j) best…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 37, ones = 0…