Sum of Squares of Special Elements - Problem

You are given a 1-indexed integer array nums of length n.

An element nums[i] of nums is called special if i divides n, i.e. n % i == 0.

Return the sum of the squares of all special elements of nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 21
💡 Note: Array length n=4. Special indices are 1,2,4 (since 4%1=0, 4%2=0, 4%4=0). Elements are nums[0]=1, nums[1]=2, nums[3]=4. Sum of squares: 1² + 2² + 4² = 1 + 4 + 16 = 21
Example 2 — Prime Length
$ Input: nums = [2,7,1,19,18,3,1]
Output: 63
💡 Note: Array length n=7. Since 7 is prime, only index 1 and 7 divide 7. Special elements are nums[0]=2 and nums[6]=1. Sum of squares: 2² + 1² = 4 + 1 = 5
Example 3 — Single Element
$ Input: nums = [5]
Output: 25
💡 Note: Array length n=1. Only index 1 divides 1. Special element is nums[0]=5. Sum of squares: 5² = 25

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Sum of Squares of Special Elements INPUT 1-indexed array nums i=1 i=2 i=3 i=4 1 2 3 4 n = 4 (length) Special Condition: n % i == 0 Divisors of 4: 1, 2, 4 Special indices: 1, 2, 4 Special values: 1, 2, 4 ALGORITHM STEPS 1 Initialize sum = 0, n = 4 2 Find Divisors Loop i from 1 to n Check if n % i == 0 i=1 i=2 i=3 i=4 4%1=0 4%2=0 4%3=1 4%4=0 OK OK NO OK 3 Square and Add For each special i: sum += nums[i]^2 4 Return Sum Output final result FINAL RESULT Squares of Special Elements: i=1: nums[1]^2 = 1^2 = 1 Special (4%1=0) i=2: nums[2]^2 = 2^2 = 4 Special (4%2=0) i=3: SKIPPED Not special (4%3=1) i=4: nums[4]^2 = 4^2 = 16 Special (4%4=0) Sum = 1 + 4 + 16 OUTPUT 21 OK - Verified Key Insight: An element is "special" if its 1-indexed position divides the array length evenly. For n=4, divisors are 1, 2, and 4. We square values at these indices and sum them: 1² + 2² + 4² = 21. TutorialsPoint - Sum of Squares of Special Elements | Direct Divisor Finding Approach
Asked in
Google 25 Microsoft 20 Amazon 15
12.5K Views
Medium Frequency
~12 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen