887939. Sum of Squares of First n Natural Numbers

Easy

Sum of Squares of First n Natural Numbers

Summary

Given a positive integer n, find the sum of squares of the first n natural numbers. This problem is a classic example of a mathematical algorithm, where we need to calculate the sum of squares of integers from 1 to n.

Detailed Explanation

The key concept involved in this problem is the formula for the sum of squares of the first n natural numbers. The formula is given by:

1^2 + 2^2 + ... + n^2 = Σ(i^2) from i=1 to n

To calculate the sum, we can use a simple loop that iterates from 1 to n, and at each iteration, we add the square of the current number to our running total.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable sum to 0.
  2. Iterate from 1 to n.
  3. At each iteration, calculate the square of the current number (i) and add it to sum.
  4. Return sum as the result.

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int sumOfSquares(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i * i;
    }
    return sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.