0

Although I have used only one loop, I don't think the time complexity of my code is O(n). Could anyone please explain me the time complexity of the code below.

public class PatternPyramid {

    public static void main(String[] args) {

        int rows = 15;
        int i = 0;
        int j = 0;
        int k = rows - 1;

        while (i < rows) {

            if (j < k) {
                System.out.print(" ");
                j++;
            } else if (j < rows) {
                j++;
                System.out.print("* ");
            } else {
                j = 0;
                i++;
                k--;
                System.out.println();
            }
        }
    }
}
Community
  • 1
  • 1
  • Aside from main question, those `continue` statements are redundant as they are always last instructions loop can invoke in that scenarios. – Pshemo Jul 25 '20 at 18:56
  • @Pshemo thanks for your correction. I have edited my question. Now can you please explain me the time complexity of this code? – Mulkraj Singh Jul 25 '20 at 19:06

2 Answers2

1

The time complexity is O(n2), where n is the number of rows.

It requires n iterations to print each row of n characters. Furthermore, it requires n iterations to print each of the new lines.

Ergo, the time complexity is:

O(n * n + n)
= O(n2 + n)
= O(n2)

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0
for (int i=0; i<rows; i++) {
    for(int j=i; j<rows;j++)
        System.out.print(" ");
    
    for(int k=0; k<=i; k++)
        System.out.print("* ");
                
    System.out.println();
}

Your code could be transformed into for loops like this, as it can be seen that outer loop run O(rows) times, and the loop for spaces runs rows-i times for each iteration whereas loop for asterisks run i times. Combining them would result in the inner loops running rows times.

Thus total time complexity would be O(rows^2)

Osama A.Rehman
  • 912
  • 1
  • 6
  • 12