Sum of Squares of Special Elements (LeetCode 2778): Solution and Explanation

Easy
Array
Enumeration

The array is indexed from 1 and has length n. An element is special when its position divides n. Return the sum of the squares of the special elements.

Intuition

The word special is only about positions, never about values. Position i is special exactly when n % i == 0, so the special positions are the divisors of the array length.

That means the set of positions is decided before you even look at the values. For n = 6 the divisors are 1, 2, 3 and 6, so only those four elements matter, whatever they contain.

Once the positions are known, the rest is a running sum of squares. With n at most 50, testing every position from 1 to n is already fast.

Approach: Divisor scan

  1. Let n = len(nums) and start total = 0.
  2. For every position i from 1 to n, test whether n % i == 0.
  3. If it divides, add nums[i - 1] * nums[i - 1] to total (shift by one because arrays are 0-indexed in code).
  4. Return total.

Step-by-step example

nums = [1,2,3,4]
  1. n = 4 and total = 0.
  2. i = 1: 4 % 1 = 0, so nums[1] = 1 is special. total = 1.
  3. i = 2: 4 % 2 = 0, so nums[2] = 2 is special. total = 1 + 4 = 5.
  4. i = 3: 4 % 3 = 1, so position 3 is skipped.
  5. i = 4: 4 % 4 = 0, so nums[4] = 4 is special. total = 5 + 16 = 21, which is returned.

Code: Python, Java, C++

1class Solution:
2    def sumOfSquares(self, nums: List[int]) -> int:
3        n = len(nums)
4        total = 0
5        for i in range(1, n + 1):
6            if n % i == 0:
7                total += nums[i - 1] * nums[i - 1]
8        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n positions gets one modulo test and at most one multiplication.

Space

O(1)

Only the loop counter and the running total are stored.

Other approaches

Divisor pairs up to sqrt(n) (time O(sqrt(n)), space O(1))

Loop i only while i * i <= n. Each divisor i gives its partner n / i, so add both squares (once when they are equal). This is faster for huge n but is overkill when n is at most 50.

Common mistakes

  • Using 0-based positions in the test. n % 0 is a division by zero, and n % (k) for 0-based k checks the wrong positions.
  • Testing the value instead of the position, such as n % nums[i] == 0.
  • Forgetting the shift when reading the value: position i lives at nums[i - 1].

Frequently asked questions

Can the answer overflow a 32-bit integer?

No. There are at most 6 divisors of a number up to 50 and each square is at most 2500, so the total stays tiny.

Are the first and last elements always special?

Yes. 1 divides every n and n divides itself, so positions 1 and n are always included. With n = 1 they are the same element.

Why does a prime length give only two special elements?

A prime n has no divisors other than 1 and itself, so only the first and the last element are squared and added.