Problem overview
The method sumOfSquares receives a non-negative integer n and returns 1² + 2² + 3² + ... + n². For n = 3 the terms are 1, 4 and 9, so the answer is 14. For n = 0 there are no terms to add, and the answer is 0.
Approach: accumulate in a variable
The sum is built one term at a time. Keep a variable that starts at 0, visit every number from 1 to n, and add the square of each number to the variable. When the loop ends, the variable holds the whole sum. This is the standard accumulator pattern, and it is the same shape you will use for products, counts and maximums later in the chapter.
The work is one addition per number, so the time is proportional to n, and the only extra memory is the running total and the loop variable.
Step by step
- Declare
sumwithvarand start it at 0. It has to change inside the loop, sovalwould not work: avalcan't be reassigned. Starting at 0 means "nothing added yet", and 0 doesn't affect an addition. Scala infers the typeIntfrom the literal. - Loop with
for (i <- 1 to n). The expression1 to nis a range that includes both ends. The arrow<-reads "for eachitaken from this range". - Add
i * itosumwith+=. The linesum += i * iis shorthand forsum = sum + i * i. The multiplication happens first. - Return
sumafter the loop. The loop only collects the terms; the method still has to hand the result back.
The solution in Scala
class Solution {
def sumOfSquares(n: Int): Int = {
var sum = 0
for (i <- 1 to n) {
sum += i * i
}
return sum
}
}
For n = 3 the loop runs three times:
i | Added | sum afterwards |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 4 | 5 |
| 3 | 9 | 14 |
Language details
1 to nand1 until ndiffer by one element.toincludesn,untilstops before it. Withuntilthe answer forn = 3would be 1 + 4 = 5.- When
nis 0,1 to 0is an empty range. The loop body never runs and the method returns the initial 0, which is correct without a special case. - Scala has no
++operator, which is why the update is written+=. - The last expression of a block is its value in Scala, so a version that ends with just
sumwould also work. The lesson uses an explicitreturn, which is fine here.
Complexity
The loop runs exactly n times and each pass does a constant amount of work, so the time is O(n). The method stores only sum and the loop variable, so the extra space is O(1).
Edge cases and common mistakes
- Using
untilinstead ofto. This leaves outn²and gives a result that is too small. - Starting the range at 0. It is harmless, since 0 squared is 0, but it does one pointless pass.
- Declaring
suminside the loop. Then it starts again from 0 on every pass and only the last square survives. - Int overflow. An
Intholds values up to 2147483647 and wraps silently past that. The sum forn = 1000is 333833500, which fits, butsumOfSquares(2000)returns -1626300296, because the true value 2668667000 is too large. ALongwould be needed for bigger inputs.
Testing
Good inputs to try: n = 0 gives 0, n = 1 gives 1, n = 3 gives 14 and n = 10 gives 385.
