Sum a Billion Squares Without a List

Easy ⏱ 8 min 76% acceptance ★★★★★ 4.6
Write sum_squares(n) computing the sum of squares 1²+…+n² with a generator expression inside sum() — parentheses, not brackets — so memory stays O(1) no matter how large n is. A list comprehension here would allocate n elements for nothing.

Examples

Example 1
Input
sum_squares(4)
Output
30
Explanation

1 + 4 + 9 + 16.

Constraints

  • Generator expression, not a list.
  • No intermediate list allowed.

Topics

Iterators & Generatorsgenerator expression

Companies

MetaNetflixGoldman Sachs

Hints

Hint 1

sum(i * i for i in range(1, n + 1)).

Hint 2

No extra parentheses needed inside a single-argument call.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.