711657. Pattern 5

Basic

Pattern 5 ==Triangles, anyone?== #711657

Summary

Generate a triangle pattern of asterisks (*) using a given input integer n. The pattern should have n levels. For example, if n is 3, the output would be:

*
***
*****

The problem involves generating a specific pattern based on an input value.

Detailed Explanation

To generate this pattern, we can use a simple algorithm that iterates from level 1 to n. At each level, we print the number of asterisks required for that level. We start with 1 asterisk at level 1, then 3 asterisks at level 2, and so on.

Here's a step-by-step breakdown:

  1. Initialize an integer variable i to 1.
  2. Loop until i is less than or equal to n.
  3. Print i number of asterisks (*) followed by a newline character (\n).
  4. Increment i by 2 for the next iteration.

Time complexity: O(n), as we only iterate n times. Space complexity: O(1), as we don't use any extra space that scales with input size.

Optimized Solutions

Java

View on GeeksforGeeks
public static void printTriangle(int n) {
    int i = 1;
    while (i <= n) {
        for (int j = 0; j < i; j++) {
            System.out.print("*");
        }
        System.out.println();
        i += 2;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.