Skip to content
Official PYQ · 2014

GATE CS 2014 Set 3 Q10 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Let AA be the square matrix of size n×nn \times n. Consider the following pseudocode. What is the expected output?

C=100;
for i=1 to n do
    for j=1 to n do
    {
        Temp = A[i][j]+C;
        A[i][j] = A[j][i];
        A[j][i] = Temp -C;
    }
for i=1 to n do
    for j=1 to n do 
        output (A[i][j]);
Choose one option
View worked solution

Answer: A

Let's trace the effect of the nested loops on the elements of the matrix AA:

  • For any off-diagonal pair (i,j)(i, j) where i≠ji \neq j, the loop visits this pair twice: once when the outer loop index is ii and the inner loop index is jj, and once when the outer loop index is jj and the inner loop index is ii.
  • During the first visit (say at (i,j)(i, j)):
    Temp=A[i][j]+C\text{Temp} = A[i][j] + C
    A[i][j]=A[j][i]A[i][j] = A[j][i]
    A[j][i]=Temp−C=(A[i][j]+C)−C=A[i][j]A[j][i] = \text{Temp} - C = (A[i][j] + C) - C = A[i][j]
    This successfully swaps the values of A[i][j]A[i][j] and A[j][i]A[j][i].
  • During the second visit (at (j,i)(j, i)):
    The same swap operation is executed again on the already-swapped elements, which restores them to their original values.
  • For diagonal elements where i=ji = j, the operation simplifies to:
    Temp=A[i][i]+C\text{Temp} = A[i][i] + C
    A[i][i]=A[i][i]A[i][i] = A[i][i]
    A[i][i]=Temp−C=A[i][i]A[i][i] = \text{Temp} - C = A[i][i]
    Thus, diagonal elements remain unchanged.

Since all off-diagonal elements are swapped twice and diagonal elements are unchanged, the final matrix is identical to the original matrix AA.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions