Problem overview
The method printStars(_ n: Int) prints n lines. Line number i holds i stars. It returns nothing: the output is what the method prints. For n = 5 the output is:
*
**
***
****
*****
Approach: grow one row at a time
Each row is the previous row plus one more star. So instead of counting how many stars a row needs, keep a string that starts empty, and in every iteration add a star and print the string. The first pass prints one star, the second two, and so on, and the loop needs no inner loop and no arithmetic.
An alternative is a nested loop, where the outer loop picks the row and the inner loop prints that many stars. It works, but it does more bookkeeping for the same output.
Step by step
- Create the row string. Declare
strwithvar, since it changes later, and set it to"". - Loop once per row.
for _ in 0..<nruns exactlyntimes. The half-open range0..<nleaves outn. The loop only counts rows and never reads the counter, so the loop variable is_. - Add a star.
str += "*"appends one star to the end of the string. - Print the row.
print(str)writes the string followed by a newline, so each row lands on its own line. It goes inside the loop, after the star is added.
The solution in Swift
class Solution {
func printStars(_ n: Int) {
var str = ""
for _ in 0..<n {
str += "*"
print(str)
}
}
}
The Swift details worth a closer look:
- No return value. The method has no
->in its signature, so it returnsVoid. The lesson's tests look at what is printed. - Half-open and closed ranges.
0..<nhas n values and0...nhas n + 1. Using the closed range here would print one row too many. - Zero rows. For
n = 0the range0..<0is empty, so nothing is printed. - Negative
n. A range cannot end below its start, so0..<nwith a negativenstops the program. The lesson gives a positiven. - A shortcut.
String(repeating: "*", count: i)builds a row of i stars in one call, andprint(String(repeating: "*", count: 3))prints***. The lesson's version avoids the call by reusing the previous row.
Complexity
Time: O(n²). The loop runs n times, but printing row i writes i characters, and 1 + 2 + ... + n is about n²/2. The output itself has that many characters, so no solution can do better.
Space: O(n). The only extra memory is str, which grows to n characters.
Edge cases and common mistakes
- Printing after the loop. That shows only the last row, a line of n stars.
- Printing before adding the star. The first line would be empty, and the last row would be missing.
- Declaring
strinside the loop. It would reset to empty on every pass, so every line would hold a single star. - Using
let.str += "*"changes the string, so it must be avar. - Off-by-one in the range.
0...nprints n + 1 rows, and1..<nprints n - 1.
Testing
n = 1prints a single*.n = 3prints*,**and***on three lines.n = 5prints the five-row triangle above.
