Leetcode 2778. Sum of Squares of Special Elements
Leetcode problem 2778: Sum of Squares of Special Elements
Given an integer array nums
, you need to find the sum of squares of all special elements. An element nums[i]
is considered special if and only if it is divisible by the index i+1
. Note that arrays are 0-indexed.
Return the sum of squares of all special elements as defined above.
i+1
?
nums[i]
is special if it is divisible by i + 1
.nums[i]
, check if it’s divisible by i+1
(since the array is 0-indexed).n
is the length of the array since we only need to make a single pass through the array.Here is the Java implementation:
public class SumOfSquaresSpecialElements {
public int sumOfSquares(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % (i + 1) == 0) {
int square = nums[i] * nums[i];
sum += square;
}
}
return sum;
}
public static void main(String[] args) {
SumOfSquaresSpecialElements sol = new SumOfSquaresSpecialElements();
int[] nums = {1, 2, 3, 4, 5, 6};
System.out.println(sol.sumOfSquares(nums)); // Expected output: 1+4+36 = 41
}
}
sum
to 0.nums[i]
, we check if it is divisible by i+1
. If true,nums[i]
and add it to sum
.sum
which holds the sum of squares of all special elements.This approach ensures that the solution is efficient and easy to understand.
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?