We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sum of Squares of Special Elements

Number: 2844

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a 1-indexed integer array nums of length n, an element nums[i] is considered special if i divides n (i.e., n % i == 0). The challenge is to return the sum of the squares of all special elements in nums.


Key Insights

  • Because the array is 1-indexed, elements correspond to indices 1 through n.
  • A special element is selected only if the index divides the total length (n) evenly.
  • We can iterate over indices from 1 to n, check the divisibility condition, and if it holds, square the element and add it to the total.
  • The constraints are small (n up to 50), so a simple O(n) solution is efficient.

Space and Time Complexity

Time Complexity: O(n) – We iterate through the array once. Space Complexity: O(1) – Only a few additional variables are needed.


Solution

We solve this problem by iterating over indices from 1 to n. For each index i, we check if n % i equals 0; if the check passes, the corresponding element (remembering to adjust for 0-indexing in most programming languages) is squared and added to the result. The final accumulated sum is then returned.


Code Solutions

# Define the function that calculates the sum of squares of special elements.
def sum_of_squares(nums):
    # n is the length of the nums array
    n = len(nums)
    # Initialize the variable that will hold the sum.
    result = 0
    # Iterate through the array using 1-indexed approach.
    for i in range(1, n + 1):
        # Check if i divides n (special element condition)
        if n % i == 0:
            # Since nums is 0-indexed in Python, index i-1 corresponds to nums[i]
            result += nums[i - 1] ** 2
    # Return the final result.
    return result

# Example usage:
print(sum_of_squares([1, 2, 3, 4]))  # Expected output: 21
← Back to All Questions