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. n % i == 0
.
Return the sum of the squares of all special elements of nums
.
Input: nums = [1, 2, 3, 4]
Output: 17
Explanation:
- nums[1] is special as 4 % 1 == 0 -> 1^2
- nums[2] is special as 4 % 2 == 0 -> 2^2
- nums[4] is special as 4 % 4 == 0 -> 4^2
- Sum of squares = 1^2 + 2^2 + 4^2 = 17
nums
contain negative integers?
nums
can contain negative integers.n
?
n
is 1. There’s no specific maximum value given, but you can assume typical constraints for such problems on LeetCode.nums
always integers?
nums
contains integers as per the problem description.i
(1-indexed). If n % i == 0
, the element nums[i-1]
(since the array is 0-indexed in Python) is a special element.Here’s the implementation based on the strategy:
def sum_of_squares(nums):
n = len(nums)
sum_of_squares = 0
for i in range(1, n + 1):
if n % i == 0:
sum_of_squares += nums[i - 1] ** 2
return sum_of_squares
# Example Usage
print(sum_of_squares([1, 2, 3, 4])) # Output: 17
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?