Pyramid Pattern

Java coding interview problem for Pattern Printing: Pyramid Pattern.

Pattern programming is one of the most common topics in Java interviews, especially for freshers and entry-level developers.

Among all pattern problems, the Pyramid Pattern is one of the first patterns every programmer learns because it teaches the fundamentals of nested loops, spaces, and character printing.

Interviewers use this problem to evaluate your understanding of:

  • Nested loops
  • Loop execution flow
  • Row and column concepts
  • Space management
  • Problem-solving skills

Learning Pyramid Patterns also helps you solve more advanced pattern questions like:

  • Diamond Pattern
  • Pascal Triangle
  • Number Pyramid
  • Floyd's Triangle
  • Hollow Pyramid
  • Butterfly Pattern

What is a Pyramid Pattern?

A Pyramid Pattern is a pattern where characters, numbers, or symbols are printed in the shape of a triangle.

The width of each row increases gradually while the leading spaces decrease.

For example,

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

This is called a Full Pyramid Pattern.


Why Are Pattern Programs Asked in Interviews?

Pattern programs are not asked because companies want you to print stars.

Instead, they test whether you understand:

  • Nested loops
  • Logical thinking
  • Breaking a problem into smaller steps
  • Row-column relationships
  • Space calculations

Once you master pattern problems, solving matrix and grid problems becomes much easier.


Understanding Rows and Columns

Suppose we want

n = 5

Output

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

Notice the pattern.

Row Stars
1 1
2 3
3 5
4 7
5 9

The number of stars follows

2 × Row − 1

Now observe the spaces.

Row Leading Spaces
1 4
2 3
3 2
4 1
5 0

The spaces follow

Rows − CurrentRow

Mathematical Formula

For every row

Stars

=

2 × Row − 1

Spaces

Rows − RowNumber

These two formulas solve almost every pyramid problem.


Visual Representation

For

Rows = 5
Row 1

Spaces = 4

Stars = 1

    *

--------------------

Row 2

Spaces = 3

Stars = 3

   ***

--------------------

Row 3

Spaces = 2

Stars = 5

  *****

--------------------

Row 4

Spaces = 1

Stars = 7

 *******

--------------------

Row 5

Spaces = 0

Stars = 9

*********

Pattern Output

Input

Rows = 5

Output

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

Understanding the Logic

Each row contains two parts.

First,

print spaces.

Then,

print stars.

Example

Row 4

 Space

↓

1

Stars

2 × 4 − 1

=

7

Output

 *******

The same logic repeats for every row.


Brute Force Approach

The simplest solution uses three loops.

Loop 1

Print every row.

Loop 2

Print spaces.

Loop 3

Print stars.


Algorithm

Step 1

Read the number of rows.

rows = 5;

Step 2

Start a loop from

1

to

rows

Step 3

Print spaces.

rows - row

times.

Step 4

Print stars.

2 * row - 1

times.

Step 5

Move to the next line.

Repeat until all rows are printed.


Dry Run

Input

Rows = 4

Iteration 1

Spaces = 3

Stars = 1

   *

Iteration 2

Spaces = 2

Stars = 3

  ***

Iteration 3

Spaces = 1

Stars = 5

 *****

Iteration 4

Spaces = 0

Stars = 7

*******

Approach 1 — Using Nested Loops

This is the most common interview solution.


Complete Java Program

public class PyramidPattern {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            // Print spaces
            for (int j = rows; j > i; j--) {

                System.out.print(" ");

            }

            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

Output

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

Step-by-Step Code Explanation

Step 1

Declare the number of rows.

int rows = 5;

Current value

5

Step 2

Create the outer loop.

for (int i = 1; i <= rows; i++)

This loop controls the rows.

Iterations

1

2

3

4

5

Step 3

Print spaces.

for (int j = rows; j > i; j--)

For

Row 1

Spaces printed

4

For

Row 5

Spaces printed

0

Step 4

Print stars.

for (int k = 1; k <= (2 * i - 1); k++)

Stars printed

Row Stars
1 1
2 3
3 5
4 7
5 9

Step 5

Move to the next line.

System.out.println();

Without this statement, all stars would appear on a single line.


Example Execution

Input

Rows = 3

Output

  *
 ***
*****

Input

Rows = 6

Output

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

Why Does This Work?

The solution divides every row into two sections:

  1. Leading Spaces – to align the stars in the center.
  2. Stars – where the number of stars follows the formula:
2 × Row − 1

The outer loop controls the total number of rows, while the two inner loops independently print spaces and stars. Combining these three loops creates the pyramid shape.


Advantages of This Approach

  • Easy to understand.
  • Demonstrates nested loops.
  • Frequently asked in interviews.
  • Easy to modify for other pyramid variations.
  • Uses only constant extra memory.

Drawbacks

Although this is the standard interview solution, interviewers often ask follow-up questions such as:

  • Can you print the pyramid using recursion?
  • Can you create a reusable method?
  • Can you print a hollow pyramid?
  • Can you print an inverted pyramid?
  • What is the time complexity?
  • Can you replace stars with numbers or alphabets?

In Part 2, we'll cover:

  • Reusable printPyramid() Method
  • Pyramid Variations
  • Hollow Pyramid
  • Inverted Pyramid
  • Time and Space Complexity
  • Common Interview Mistakes
  • Interview Follow-up Questions
  • Related Pattern Problems
  • Key Takeaways
  • Interview Tips

Approach 2 — Using a Reusable Method

Instead of writing the pyramid logic directly inside the main() method, we can create a reusable method.

This approach improves:

  • Code readability
  • Reusability
  • Maintainability
  • Unit testing

Java Program

public class PyramidPatternMethod {

    static void printPyramid(int rows) {

        for (int i = 1; i <= rows; i++) {

            // Print leading spaces
            for (int j = rows; j > i; j--) {

                System.out.print(" ");

            }

            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {

                System.out.print("*");

            }

            System.out.println();

        }

    }

    public static void main(String[] args) {

        printPyramid(5);

    }

}

Output

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

Pattern Variation 1 — Inverted Pyramid

The pyramid can also be printed upside down.


Output

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

Java Program

public class InvertedPyramid {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = rows; i >= 1; i--) {

            // Print leading spaces
            for (int j = rows; j > i; j--) {

                System.out.print(" ");

            }

            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

Pattern Variation 2 — Hollow Pyramid

Instead of filling every position with a star, print only the border.


Output

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

Java Program

public class HollowPyramid {

    public static void main(String[] args) {

        int rows = 5;

        for (int i = 1; i <= rows; i++) {

            // Print spaces
            for (int j = rows; j > i; j--) {

                System.out.print(" ");

            }

            // Print stars
            for (int k = 1; k <= (2 * i - 1); k++) {

                if (k == 1 || k == (2 * i - 1) || i == rows) {

                    System.out.print("*");

                } else {

                    System.out.print(" ");

                }

            }

            System.out.println();

        }

    }

}

Pattern Variation 3 — Number Pyramid

Replace stars with numbers.


Output

    1
   121
  12321
 1234321
123454321

Pattern Variation 4 — Alphabet Pyramid

Replace stars with alphabets.


Output

    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA

Dry Run

Input

Rows = 3

Processing

Row 1

Spaces = 2

Stars = 1

  *

----------------

Row 2

Spaces = 1

Stars = 3

 ***

----------------

Row 3

Spaces = 0

Stars = 5

*****

Time Complexity

Suppose

n

is the number of rows.


Standard Pyramid

Operation Complexity
Time O(n²)
Space O(1)

Each row prints spaces and stars.


Hollow Pyramid

Operation Complexity
Time O(n²)
Space O(1)

Inverted Pyramid

Operation Complexity
Time O(n²)
Space O(1)

Comparison of Approaches

Approach Time Space Recommended
Basic Nested Loops O(n²) O(1) ✅ Best for Beginners
Reusable Method O(n²) O(1) Production Ready
Hollow Pyramid O(n²) O(1) Intermediate
Inverted Pyramid O(n²) O(1) Interview Favorite

Common Mistakes

Mistake 1

Printing the wrong number of spaces.

Wrong

for (int j = 1; j <= rows; j++)

Correct

for (int j = rows; j > i; j--)

Mistake 2

Printing the wrong number of stars.

Wrong

i

Correct

2 * i - 1

Mistake 3

Forgetting System.out.println().

Without it, all rows appear on one line.

Correct

System.out.println();

Mistake 4

Using the wrong loop variable.

Wrong

k <= rows

Correct

k <= (2 * i - 1)

Mistake 5

Confusing row count with star count.

Remember:

Rows

↓

Controls height

Stars

↓

Controls width

Interview Follow-up Questions

Q1. What is the logic behind a Pyramid Pattern?

Q2. Why do we print spaces first?

Q3. Why does the number of stars follow 2 × row − 1?

Q4. Can you print a Hollow Pyramid?

Q5. Can you print an Inverted Pyramid?

Q6. Can you replace stars with numbers?

Q7. Can you print an Alphabet Pyramid?

Q8. What is the time complexity?

Q9. Can you solve this using recursion?

Q10. Can you write a reusable printPyramid() method?


Related Pattern Problems

  • Right Triangle Pattern
  • Left Triangle Pattern
  • Inverted Pyramid
  • Hollow Pyramid
  • Diamond Pattern
  • Floyd's Triangle
  • Pascal's Triangle
  • Number Pyramid
  • Alphabet Pyramid
  • Butterfly Pattern

Key Takeaways

  • A Pyramid Pattern is created using nested loops.
  • Every row consists of:
    • Leading spaces
    • Stars (or numbers/alphabets)
  • Leading spaces follow:
Rows − Current Row
  • Stars follow:
2 × Row − 1
  • Always print spaces before stars.
  • The standard pyramid solution runs in O(n²) time and uses O(1) extra space.

Frequently Asked Interview Questions

Q1. Why do we need nested loops?

The outer loop controls the rows, while the inner loops print spaces and stars for each row.


Q2. Why do stars increase by 2 in every row?

The pattern follows the mathematical formula:

Stars = 2 × Row − 1

Example

Row Stars
1 1
2 3
3 5
4 7
5 9

Q3. Why are spaces printed before stars?

Printing leading spaces centers the stars, creating the pyramid shape.


Q4. Can we print numbers instead of stars?

Yes.

Replace

System.out.print("*");

with the required number logic.


Q5. What is the difference between a Full Pyramid and a Hollow Pyramid?

Full Pyramid Hollow Pyramid
Every position is filled with stars. Only the boundary is printed with stars.
Simpler logic. Requires additional conditional checks.

Interview Tip

If an interviewer asks:

"Print a Pyramid Pattern in Java."

Start by explaining that the pattern is divided into three tasks for every row:

  1. Print the required number of leading spaces.
  2. Print the required number of stars, following the formula 2 × row − 1.
  3. Move to the next line.

Write the standard nested-loop solution first because it is the most common interview approach. Once it works, mention that the same logic can be extended to print Hollow Pyramids, Inverted Pyramids, Diamond Patterns, Number Pyramids, and Alphabet Pyramids by changing only the inner loop logic while keeping the outer loop structure unchanged.