Problem overview
The method sumOfSquares takes a non-negative integer n and returns the sum of the squares 1 * 1 + 2 * 2 + ... + n * n. For n = 3 the answer is 1 + 4 + 9 = 14.
Approach: an accumulator
The method keeps a running total. It starts at 0, a loop visits each number from 1 to n, and each pass adds that number's square to the total. When the loop is done, the total is the answer. Squaring a number is just multiplying it by itself.
Step by step
- Declare the total with
var sum = 0. It usesvarbecause it changes in the loop, and Swift infers the typeInt. - Loop with
for number in 1...n. The closed range includes both ends, sonitself is squared. - Add the square with
sum += number * number. - Return
sumafter the loop.
The solution in Swift
class Solution {
func sumOfSquares(_ n: Int) -> Int {
var sum = 0
for number in 1...n {
sum += number * number
}
return sum
}
}
The method gives 14 for 3, 1 for 1 and 385 for 10.
Swift details worth knowing:
- Closed ranges must be ordered.
1...nrequiresnto be at least 1. Forn = 0the range would be1...0, whose upper bound is below its lower bound, and a range like that makes the program crash at run time rather than producing an empty loop. The statement allows 0 (a non-negative integer), so if that input matters, guard against it first:if n < 1 { return 0 }, or usestride(from: 1, through: n, by: 1), which is empty forn = 0. - Compound assignment.
x += ymeansx = x + y. - Overflow traps.
Intis 64 bits and an overflowing operation stops the program with a crash; it doesn't wrap. The total fits fornup to 3,000,000, but 3,200,000 overflows. - Loop variable.
numberis created by the loop and is a constant inside the body.
Following n = 3
The total starts at 0. With number equal to 1 it becomes 1. With 2 it becomes 5, and with 3 it becomes 14. After the third pass the range is exhausted, the loop ends, and the method returns 14. Each pass adds exactly one square, so the number of passes equals n.
Complexity
Time: O(n). The loop makes n passes, each doing a multiplication and an addition.
Space: O(1). Only the total and the loop variable are stored.
A closed formula exists: the sum equals n * (n + 1) * (2 * n + 1) / 6, which gives 55 for n = 5. The loop is simpler to write and to trust, and it is what this lesson practises.
Edge cases and common mistakes
- n = 0. The expected answer is 0, but the closed range
1...0crashes, as described above. - n = 1. The range holds one value, and the answer is 1.
- Starting at 0. It adds 0, which is harmless but unnecessary.
- Using
1..<n. The loop would skipn, andsumOfSquares(3)would return 5. - Adding the number instead of its square.
sum += numberwould return 6 forn = 3. - Declaring the total inside the loop. It would reset on each pass.
Testing
sumOfSquares(3)gives 14.sumOfSquares(1)gives 1.sumOfSquares(10)gives 385.sumOfSquares(5)gives 55.
