Sum of Squares of Special Elements — LeetCode 2778 Python Solution

EasyArrayEnumeration
Problem
#2778
Reading time
2 min

The problem

You are given a 1-indexed integer array nums of length n. An element nums[i] of nums is called special if i divides n, i.e.

Example

Input
nums = [1,2,3,4]
Output
21
Explanation
There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4.

Python solution

Python
class Solution:
    def sumOfSquares(self, nums: List[int]) -> int:
        n = len(nums)
        return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2778. Sum of Squares of Special Elements?
LeetCode 2778. Sum of Squares of Special Elements is rated Easy on LeetCode.
What topics does LeetCode 2778. Sum of Squares of Special Elements cover?
LeetCode 2778. Sum of Squares of Special Elements is tagged Array and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview