algoadvance

Leetcode 2778. Sum of Squares of Special Elements

Problem Statement

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.

Clarifying Questions

  1. Clarification on Indexing: Since arrays are typically 0-indexed, should we consider divisibility by i+1?
    • Yes, an element nums[i] is special if it is divisible by i + 1.
  2. Input and Output Constraints: Are there any constraints or edge cases we should be aware of?
    • The array could be empty. If it’s empty, the sum should be 0.
    • Elements in the array can be positive or negative, and possibly zero.

Strategy

  1. Initialize a sum: Start with a sum of 0.
  2. Iterate through the array: For each element nums[i], check if it’s divisible by i+1 (since the array is 0-indexed).
  3. Calculate square and add to the sum: If an element satisfies the condition, square it and add it to the sum.
  4. Return the total sum after iteration.

Time Complexity

Code

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
    }
}

Explanation

This approach ensures that the solution is efficient and easy to understand.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI