Leetcode 2778. Sum of Squares of Special Elements
You’re given a 1-indexed integer array nums
of length n
.
An element nums[i]
is special if i
divides n
, i.e., n % i == 0
.
Return the sum of the squares of all special elements.
n
(length of nums
)?
1 <= n <= 10^4
.special
?
i = 1
always divides n
, there’s at least one special element.i
from 1
to n
.i
, check if i
divides n
without leaving a remainder (i.e., n % i == 0
).n = 1
) and largest (n = 10^4
) possible values of the array length efficiently.#include <iostream>
#include <vector>
int sumOfSquares(std::vector<int>& nums) {
int n = nums.size();
int sum = 0;
for (int i = 1; i <= n; ++i) {
if (n % i == 0) {
sum += nums[i - 1] * nums[i - 1]; // Since the array is 1-indexed based on the problem
}
}
return sum;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5}; // Example input
std::cout << sumOfSquares(nums) << std::endl; // Expected output: 1 + 4 + 25 = 30
return 0;
}
This implementation ensures that it efficiently computes the sum of squares for special elements in linear time with respect to the size of the input array.
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?