711660. Pattern 8

Basic

Pattern 8

Summary

The problem, known as "Pattern 8", involves generating a specific triangle pattern based on input values. The goal is to create an algorithm that prints a triangle with asterisks (*) and spaces, following a particular pattern.

Detailed Explanation

To solve this problem, we'll break it down into smaller steps:

Algorithmic Approach

We can approach this problem by iterating through each row of the triangle and printing the required number of asterisks and spaces. The key is to calculate the correct number of spaces for each row based on its position in the triangle.

Step-by-Step Solution

Here's a step-by-step breakdown of the solution:

  1. Start with an empty string output that will store the final triangle pattern.
  2. Iterate through each row i from 1 to n, where n is the input value.
  3. For each row, calculate the number of spaces needed by subtracting the current row number (i) from the maximum number of rows (n). This will give us the correct number of spaces for that row.
  4. Print the calculated number of spaces followed by a specified number of asterisks (*) equal to i.
  5. Add a newline character (\n) after printing each row.

Time and Space Complexity Analysis

The time complexity of this algorithm is O(n), where n is the input value, since we're iterating through each row once. The space complexity is also O(n) because we're storing the final triangle pattern in an output string.

Optimized Solutions

Here are optimized solutions for various programming languages:

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int n = 5; // input value
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.