⚡ TL;DR
Create a mirrored/right-aligned triangle star pattern in Dart. Includes StringBuffer for efficiency, output verification, and beginner practice variations.
The left triangle (right-aligned) star pattern mirrors the classic right triangle. Stars hug the right edge, so spaces lead each row — essential for understanding indentation control with loops.
What We’ll Build
*
**
***
****
*****Each row i has n - i spaces followed by i stars.
Approach 1: Nested For Loops with StringBuffer
import 'dart:io';
void main() {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuffer row = StringBuffer();
// Leading spaces
for (int j = i; j < n; j++) {
row.write(" ");
}
// Stars
for (int k = 1; k <= i; k++) {
row.write("*");
}
print(row.toString());
}
}Output
*
**
***
****
*****Approach 2: String Repetition (Cleaner)
void main() {
int n = 5;
for (int i = 1; i <= n; i++) {
print(" " * (n - i) + "*" * i);
}
}Output
*
**
***
****
*****Approach 3: With Padding Numbers
void main() {
int n = 5;
for (int i = 1; i <= n; i++) {
String spaces = " " * (n - i);
String nums = "";
for (int j = 1; j <= i; j++) {
nums += j.toString() + " ";
}
print(spaces + nums.trim());
}
}Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Approach 4: Right Triangle Combo
void main() {
int n = 5;
for (int i = 1; i <= n; i++) {
print(" " * (n - i) + "*" * i);
}
}Output
*
**
***
****
*****Dart Console Tips
- No
endparameter —print()always ends with newline viastdout.writeln() - String multiplication —
"*" * 5is a full clone - StringBuffer vs + — prefer
StringBufferfor heavy loop building (O(n²) vs O(n³) with+=)
// ⚠️ Inefficient
String result = "";
for (int i = 0; i < 1000; i++) {
result += "x"; // Each += creates new string
}
// ✅ Efficient
StringBuffer buf = StringBuffer();
for (int i = 0; i < 1000; i++) {
buf.write("x");
}
String result = buf.toString();Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(n²) — total characters = 1+2+3+…+n = n(n+1)/2 |
| Space | O(n) per row |
Practice Variations
- Solid square:
nstars per row (no leading spaces) - Hollow diamond: outline only
- Sandglass: pyramid + inverted pyramid
- X shape: stars on diagonals only
Verification with Tests
void main() {
int n = 5;
List<String> outputs = [];
for (int i = 1; i <= n; i++) {
outputs.add(" " * (n - i) + "*" * i);
}
List<String> expected = [
" *",
" **",
" ***",
" ****",
"*****"
];
if (outputs.toString() == expected.toString()) {
print("✓ Test passed");
}
}Next: Inverted Pyramid Star Pattern in Dart
Related Patterns
FAQ
How do you print the Left Triangle Star pattern in Dart?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Dart implementation with expected output is shown in the sections above.
What is the time complexity of the Left Triangle Star pattern in Dart?
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.
