Python Program to Print Hollow Rectangle Pattern



When we start programming then printing different star patterns helps us build our logic and problem-solving skills. One of the easiest and beginner patterns is the hollow rectangle pattern. In this article, we are going to learn how we can print the hollow rectangle pattern using different approaches in Python.

Hollow Rectangle Pattern

A Hollow rectangle pattern is a rectangle-shaped pattern printing of stars where the stars are present only on the boundaries of the rectangle. The rectangle is hollow, i.e., the stars are printed only on the boundaries of the rectangle, while the inner area remains empty.

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

Using Nested Loop Approach

In this approach, we use a nested loop to print a hollow rectangle star pattern. The outer loop handles each row, and the inner loop handles each column. We check if it is the first or last row, then we print the star; otherwise, we print the space in between.

Example

rows = 6
cols = 5 
for i in range(rows):
    for j in range(cols):
        if i == 0 or i == rows - 1 or j == 0 or j == cols - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()

The output of the above program is as follows -

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

Time Complexity: O(n × m).

Using String Concatenation Approach

In this approach, we print the hollow rectangle pattern by constructing a string row by row. In this approach, for the first and last row, we create a string of stars of length equal to the number of columns. For the middle rows, we only create a string that has a star only at the start and the end, and print spaces in between.

Example

rows = 4
cols = 5
for i in range(rows):
    if i == 0 or i == rows - 1:
        print("*" * cols)
    else:
        print("*" + " " * (cols - 2) + "*")

The output of the above program is as follows -

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

Time Complexity: O(n × m).

Updated on: 2025-05-05T15:44:25+05:30

8 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements