coder005 - 6 months ago 42

Java Question

I have printed this pattern using one loop:

`*`

**

***

****

*****

String s = "";

for (i = 1; i <= n; ++i) {

s += "*";

System.out.println(s);

}

Now i want how to print following patterns using only one loop.

`1)`

*

* *

* * *

* * * *

* * * * *

2)

* * * * *

* * * *

* * *

* *

*

3)

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

and other similar patterns using only

Answer

I want optimization. The time complexity of two loops will be O(n^2) whereas for only one loop it will be O(n). And O(n) < O(n^2).

You realise that 99.999% of the time will be spent updating the console. If you want to save time, don't write anything. The time taken to loop is trivial by comparison.

BTW The number of stars you produce will be O(N^2) so the time complexity with be O(N^2) whether you use 1, 2 or 3 loops.