#2778

Sum of Squares of Special Elements

Easy
ArrayEnumerationEnumerationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can directly compute the sum of squares of the special elements by iterating through the indices that divide n, which reduces unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to hold the sum of squares.
  2. 2Step 2: Loop through each index from 1 to n (inclusive).
  3. 3Step 3: For each index, if it divides n, add the square of nums[i-1] to the sum.
  4. 4Step 4: Return the total sum.
solution.py9 lines
1# Full working Python code
2
3def sum_of_squares(nums):
4    n = len(nums)
5    total_sum = 0
6    for i in range(1, n + 1):
7        if n % i == 0:
8            total_sum += nums[i - 1] ** 2
9    return total_sum

Complexity note: The optimal solution also runs in O(n) time, as we only loop through the array once, and uses O(1) space since we are not using any additional data structures.

  • 1Understanding how to identify special indices is crucial for solving this problem efficiently.
  • 2Recognizing that we only need to check indices that divide n helps streamline the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.