⚡ TL;DR
Print the alphabet hollow diamond pattern in Swift. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Alphabet Hollow Diamond pattern is a classic loop exercise. Here’s the complete implementation in Swift with working code and output.
Pattern to Print
A
B B
C C
D D
E E
D D
C C
B B
AImplementation
func hollowDiamond(_ n: Int) {
for i in 1...n {
let ch = String(UnicodeScalar(64 + i)!)
if i == 1 { print(String(repeating: " ", count: n - i) + ch) } else { print(String(repeating: " ", count: n - i) + ch + String(repeating: " ", count: 2 * i - 3) + ch) }
}
for i in stride(from: n - 1, through: 1, by: -1) {
let ch = String(UnicodeScalar(64 + i)!)
if i == 1 { print(String(repeating: " ", count: n - i) + ch) } else { print(String(repeating: " ", count: n - i) + ch + String(repeating: " ", count: 2 * i - 3) + ch) }
}
}
hollowDiamond(5)Output
A
B B
C C
D D
E E
D D
C C
B B
AHow It Works
Print only the border letters of a diamond. Row i uses the i-th letter.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
Related Patterns
- Alphabet Hollow Diamond in Python
- Alphabet Hollow Diamond in Dart
- Alphabet Hollow Diamond in Go
- Repeated Letter Rows in Swift
- Alphabet Rectangle in Swift
- Hollow Alphabet Square in Swift
FAQ
How do you print the Alphabet Hollow Diamond pattern in Swift?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Swift implementation with expected output is shown in the sections above.
What is the time complexity of the Alphabet Hollow Diamond pattern in Swift?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
