712066. Pattern 12

Easy

Pattern 12

Summary

The Pattern 12 problem is about generating a double triangle pattern using asterisks (*) and spaces. The goal is to create a pattern that alternates between increasing and decreasing sequences, with each row having one more element than the previous one.

Detailed Explanation

To solve this problem, we can use a simple loop-based approach to generate the desired pattern. Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the generated pattern.
  2. Loop through the rows of the triangle (let's say up to n rows). For each row:
    • Start by adding n spaces at the beginning of the row, where n is the current row number.
    • Then, add a sequence of n asterisks (*) followed by a space.
    • To create the decreasing sequence, subtract 1 from n and repeat the process until you reach the desired length.
  3. Append each row to the result string using the newline character (\n) to separate rows.

Here's an ASCII art representation of the pattern:

    *
   * *
  * * *
 * * * *
* * * * *

Time complexity: O(n), where n is the number of rows. Space complexity: O(n), since we're storing the generated pattern in a string.

Optimized Solutions

Java

View on GeeksforGeeks
public class Pattern12 {
    public static void main(String[] args) {
        int n = 5; // adjust this value to generate different patterns
        StringBuilder result = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < n - i; j++) {
                result.append(" ");
            }
            for (int k = 0; k < 2 * i - 1; k++) {
                if (k < i) {
                    result.append("* ");
                } else {
                    result.append(" *");
                }
            }
            result.append("\n");
        }
        System.out.println(result.toString());
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.