FastPrepPrint a Diamond Pattern

Print a Diamond Pattern

Apple logoApple● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Given an integer n, return the lines of a filled diamond made of asterisks (*). The top half, including the center row, contains n rows. The bottom half mirrors the top half and excludes a second copy of the center.

There are exactly 2*n - 1 lines. For a zero-based row r, let d = |r - (n - 1)|. The line contains exactly d leading spaces followed by 2*(n - d) - 1 asterisks.

Use ordinary ASCII spaces. Preserve leading spaces, include no trailing spaces, and do not include newline characters inside any returned string.

Function

diamondLines(n: int) → String[]

Examples

Example 1

n = 1return = ["*"]

The minimum diamond contains one row with one asterisk.

Example 2

n = 3return = ["  *"," ***","*****"," ***","  *"]

The asterisk counts are 1,3,5,3,1, with 2,1,0,1,2 leading spaces. The center appears once.

Constraints

  • 1 <= n <= 30.

More Apple problems

See Apple hiring insights
public String[] diamondLines(int n) {
    // Write your solution here.
}
n1
expected["*"]
Checking account…