712036. Pattern 18

Easy

Pattern 18

Summary

The Pattern 18 problem involves generating a specific triangular pattern. The pattern is formed by printing numbers in a triangular shape, where each row has one more number than the previous row. This problem requires applying algorithmic concepts to efficiently generate and print the desired pattern.

Detailed Explanation

To solve this problem, we'll use a simple iterative approach. We'll start by initializing an empty string result that will store the generated pattern. Then, we'll iterate from 1 to n, where n is the number of rows in the triangle.

In each iteration, we'll add a new row to the result string. The length of each row will increase by 1 for each subsequent iteration. We'll fill the row with numbers starting from 1 and incrementing by 1 for each subsequent number. Finally, we'll add a newline character at the end of each row.

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

  1. Initialize an empty string result.
  2. Iterate from 1 to n (inclusive).
  3. For each iteration:
    • Calculate the length of the current row (row_length) by adding 1 to the previous row's length.
    • Fill the row with numbers starting from 1 and incrementing by 1 for each subsequent number.
    • Add a newline character at the end of the row.
    • Append the row to the result string.
  4. Return the generated pattern (result).

Time complexity: O(n) Space complexity: O(1) (since we're only storing the generated pattern)

Optimized Solutions

Java

View on GeeksforGeeks
public static String generateTriangle(int n) {
    StringBuilder result = new StringBuilder();
    for (int i = 1; i <= n; i++) {
        int rowLength = i;
        for (int j = 1; j <= rowLength; j++) {
            result.append(j).append(" ");
        }
        result.append("\n");
    }
    return result.toString();
}

DevExCode

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

© 2026 DevExCode. All rights reserved.