Hollow Rectangle Pattern - Problem

Given the width and height of a rectangle, print a hollow rectangle pattern using asterisks (*) for the borders and spaces for the interior.

A hollow rectangle has asterisks only on the top row, bottom row, leftmost column, and rightmost column. All interior positions contain spaces.

Output Format: Print each row on a separate line. Each row should have exactly width characters (asterisks and spaces).

Input & Output

Example 1 — Basic Rectangle
$ Input: width = 5, height = 3
Output: ***** * * *****
💡 Note: Top row: all 5 asterisks. Middle row: asterisk + 3 spaces + asterisk. Bottom row: all 5 asterisks.
Example 2 — Single Column
$ Input: width = 1, height = 4
Output: * * * *
💡 Note: When width is 1, every position is a border position, so all rows contain a single asterisk.
Example 3 — Single Row
$ Input: width = 6, height = 1
Output: ******
💡 Note: When height is 1, there are no middle rows, so we have one complete border row.

Constraints

  • 1 ≤ width ≤ 100
  • 1 ≤ height ≤ 100

Visualization

Tap to expand
INPUTALGORITHMRESULTRectangle DimensionsWidth5Height3Define the rectangleboundaries: 5 columnsand 3 rows total1Identify Patterns***** (border)2Apply Row Rules* * (middle)3Build RectangleRow 0: border patternRow 1: middle patternRow 2: border patternHollow Rectangle****** ******Asterisks form the borderSpaces fill the interiorPerfect hollow rectangle!Key Insight:A hollow rectangle consists of only 3 distinct row patterns:top border (all *), middle rows (* + spaces + *), and bottom border (all *).TutorialsPoint - Hollow Rectangle Pattern | Pattern-Based Construction
Asked in
Microsoft 8 Amazon 5
12.5K Views
Medium Frequency
~8 min Avg. Time
340 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen