Print Z pattern from 2D String array I am trying to print the Z pattern, but the time complexity is coming to \$O(n^2)\$. Is there any way to reduce the time complexity?

package matrix;

public class ZPattern 
{
    public static void main(String[] args) {
        String a[][] = { {"1","2","3","4","5"},
                {"a","b","c","d","e"},
                {"6","7","8","9", "f"},
                {"g","h","i","j","k"},
                {"m","n","o","p","q"}
            };
        for(int i=0;i&lt;a.length;i++)
        {
            for(int j=0;j&lt;a.length;j++)
            {
                if(i==0||i==a.length-1)
                {
                    System.out.print(a[i][j]);
                }
                else if(i+j==a.length-1)
                {
                    System.out.print(a[i][j-1]);
                }
                else
                {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
    }
}
Bug?

The output from your version:

12345
   c 
  7  
 g   
mnopq


But the output should be 

12345
   d
  8
 h
mnopq


It's unclear why you chose this.  


                    System.out.print(a[i][j-1]);



This could be 

                    System.out.print(a[i][j]);


Then it prints the output correctly.  

Avoid unnecessary comparisons in loops

You iterate over each element in the entire square and print different things based on an if/else structure.  But you don't actually have to do that.  Consider 

    public static void drawZ(String[][] matrix) {
        System.out.println(String.join("", matrix[0]));

        int n = matrix.length - 1;
        for (int i = 1; i &lt; n; i++)
        {
            int m = matrix.length - i - 1;
            for (int j = m; j &gt; 0; j--)
            {
                System.out.print(" ");
            }

            System.out.println(matrix[i][m]);
        }

        System.out.println(String.join("", matrix[n]));
    }


This is in a separate method, which makes it easy to reuse.  

This prints the first and last line separately.  So we don't need that part of the if.  

This prints the spaces separately from the line of the Z.  So we don't need those parts of the if either.  

Rather than calculating i + j - a.length - 1 on every iteration, this code just counts down from m, which it calculates once per row.  

This calls a Java 8 built-in method to join the characters in a row rather than rolling our own for loop.  

This prints the equivalent part of the matrix.  If that's not what you want, you can replace [m] with [m - 1].  That would give the original behavior.