ProgrammingHardTCS NQT · Accenture pattern
What is the time complexity of the following pseudocode, in terms of n, where the array has n elements?
What is the time complexity of the following pseudocode, in terms of n, where the array has n elements?
for (each i from 0 to n - 1)
for (each j from 0 to n - 1)
if (j > i)
break
end if
Print arr[i], arr[j]
end for
end for- A. O(n)
- B. O(n log n)
- C. O(n^2)
- D. O(1)
Correct answer: C. O(n^2)
Even though the inner loop breaks early once j>i, it still always runs at least i+1 times (j from 0 to i), so the inner work is proportional to i on each outer pass; summing 1+2+...+n is still O(n^2).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[6] = {5, 2, 9, 1, 5, 6} for (each i from 1…
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[5] = {2, 4, 6, 8, 10} Integer prefix[6]…
- What will be the output of the following pseudocode? Integer moves = 0 Function hanoi(Integer n) if (n == 0) return end if hanoi(n - 1)…
- What will be the output of the following pseudocode? Function isPalindrome(String s) Integer i = 0, j = length(s) - 1 while (i < j) if…
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[5] = {1, 2, 3, 4, 5} Integer s = 0 for (each…
- What will be the output of the following pseudocode? (Matrices are indexed from 0.) Integer mat[3][2] = {{1, 2}, {3, 4}, {5, 6}} Integer…