Skip to content

2778. Sum of Squares of Special Elements

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int sumOfSquares(vector<int>& nums) {
    const int n = nums.size();
    int ans = 0;

    for (int i = 0; i < n; ++i)
      if (n % (i + 1) == 0)
        ans += nums[i] * nums[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int sumOfSquares(int[] nums) {
    final int n = nums.length;
    int ans = 0;

    for (int i = 0; i < n; ++i)
      if (n % (i + 1) == 0)
        ans += nums[i] * nums[i];

    return ans;
  }
}
1
2
3
4
class Solution:
  def sumOfSquares(self, nums: list[int]) -> int:
    return sum(num**2 for i, num in enumerate(nums)
               if len(nums) % (i + 1) == 0)