711696. Pattern 13

Basic

Pattern 13

Summary

This problem is about generating a specific triangle pattern where each row has one more element than the previous row. The key concept involved is understanding how to iterate over the rows and columns of the pattern, considering the constraints for each row.

Detailed Explanation

To generate this pattern, we will start by creating an empty list rows that will store each row of the triangle. We then enter a loop where we keep adding elements to the current row until it reaches the desired size.

For each element in the current row, we add spaces and the element itself, followed by a newline character (\n) to start the next row. The number of spaces needed for each element is calculated based on the position of the element within the row and the previous rows. This ensures that all elements are aligned properly.

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

  1. Initialize an empty list rows to store each row of the triangle.
  2. Calculate the number of rows (n) needed for the pattern.
  3. Enter a loop where you keep adding elements to the current row until it reaches the desired size.
  4. For each element in the current row, add spaces and the element itself, followed by a newline character (\n) to start the next row.
  5. The number of spaces needed for each element is calculated based on the position of the element within the row and the previous rows.

The time complexity for this solution is O(n), where n is the total number of elements in the triangle pattern, and the space complexity is also O(n) as we store all elements in the rows list.

Optimized Solutions

Java

View on GeeksforGeeks
public class Pattern13 {
    public static void main(String[] args) {
        int n = 5; // Number of rows
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.