Sum of Squares of Special Elements — Easy Problem & Solution
An element nums[i - 1] is special when i divides n, the length of nums. Note the 1-based index i. Return the sum of the squares of all special elements.
- Difficulty: Easy
- Topics: Arrays, Math, Number Theory
- Asked at: TCS, Wipro, Capgemini
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
An element nums[i - 1] is special when i divides n, the length of nums. Note the 1-based index i.
Return the sum of the squares of all special elements.
Example 1
Input: nums = [1,2,3,4]
Output: 21
Explanation: n is 4, and 1, 2 and 4 divide it, giving 1² + 2² + 4² = 21.
Example 2
Input: nums = [2,7,1,19,18,3]
Output: 63
Explanation: n is 6, and 1, 2, 3 and 6 divide it, giving 4 + 49 + 1 + 9 = 63.
Example 3
Input: nums = [5]
Output: 25
Constraints
1 <= nums.length <= 501 <= nums[i] <= 50
How to solve Sum of Squares of Special Elements
The condition is purely positional, so loop over 1-based positions, test divisibility against the length and square the value at that position.
Approach
- Let
nbe the length ofnums. - For
ifrom1ton, checkn % i == 0. - When it holds, add
nums[i - 1] * nums[i - 1]to the total.
Why it works
Each position is tested exactly once against the exact predicate the statement names, so the sum ranges over precisely the special elements.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Using the 0-based index in the divisibility test shifts every position by one and makes
i = 0a division by zero. - Squaring values up to 50 across 50 positions stays well inside 32 bits, but squaring is easy to forget.
Reference solution
Python
from typing import List
def sumOfSquares(nums: List[int]) -> int:
n = len(nums)
return sum(nums[i - 1] ** 2 for i in range(1, n + 1) if n % i == 0)JavaScript
var sumOfSquares = function(nums) {
var n = nums.length, total = 0;
for (var i = 1; i <= n; i++) {
if (n % i === 0) total += nums[i - 1] * nums[i - 1];
}
return total;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.