Right-Angled Triangle of Stars
Description
Given n, return a right-angled triangle of stars, n rows high, as a list of rows: the first row has 1 star, the second 2, and so on, until the last row has n.
Examples
Example 1
Input: n = 3
Output: ["", "", ""]
Explanation: Row 1 has one star, row 2 two, row 3 three.
Example 2
Input: n = 1
Output: ["*"]
Explanation: One row with one star.
Example 3
Input: n = 5
Output: ["", "", "", "****", "*****"]
Explanation: Five rows, growing by one star each.
Constraints
- 1 ≤ n ≤ 100
Editorial
Approach - Build Each Row from Its Counts
Intuition
Row i, counting from 1, is just i stars. So one loop over the rows, from 1 to n, builds each row from its count: "*" * i in Python, "*".repeat(i) in Java and JavaScript, string(i, '*') in C++.
Step-by-Step Explanation
Let's trace Example 1, n = 3:
- Row 1: 1 star.
- Row 2: 2 stars.
- Row 3: 3 stars.
- Return the 3 rows.
Right-Angled Triangle of Stars — The rows, built one per step from the top; the row just built is lit.
Algorithm
- For
ifrom 1 ton, add a row ofistars. - Return the rows.
Code
class Solution {
public:
vector<string> rightTriangle(int n) {
vector<string> rows;
for (int i = 1; i <= n; i++) rows.push_back(string(i, '*')); // row i has i stars
return rows;
}
};
from typing import List
class Solution:
def rightTriangle(self, n: int) -> List[str]:
return ["*" * i for i in range(1, n + 1)] # row i has i stars
import java.util.*;
class Solution {
public List<String> rightTriangle(int n) {
List<String> rows = new ArrayList<>();
for (int i = 1; i <= n; i++) rows.add("*".repeat(i)); // row i has i stars
return rows;
}
}
var rightTriangle = function(n) {
const rows = [];
for (let i = 1; i <= n; i++) rows.push("*".repeat(i)); // row i has i stars
return rows;
};
Complexity Analysis
Time Complexity: O(n²)
There are O(n) rows of O(n) characters, and each character is written once.
Space Complexity: O(n²)
The rows of the answer.
Common Mistakes
Each of these looks right on a quick read, and the tests still reject it. The outputs below come from running the code.
Counting rows from 0. range(n)
On n = 3 it returns ["", "*", "**"]; the answer is ["*", "**", "***"]. range(n) starts at 0, so the first row has 0 stars, an empty string, and the last has n - 1. The rows run from 1 to n: range(1, n + 1).
Stopping one row short. range(1, n)
On n = 3 it returns ["*", "**"]; the answer is ["*", "**", "***"]. range(1, n) stops before n, so the last row, with n stars, is missing.
Building it upside down. "*" * (n - i + 1)
On n = 3 it returns ["***", "**", "*"]; the answer is ["*", "**", "***"]. n - i + 1 stars puts the longest row first. The triangle grows downwards: row i has i stars.
Where This Pattern Is Taught
This problem practises nested counting: for each row, how many of each character, and building the row as a string. It's taught in Python for DSA, Java for DSA, C++ for DSA and JavaScript for DSA.