Leetcode #1390: Four Divisors
In this guide, we solve Leetcode #1390 Four Divisors in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
Python Solution
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
def f(x: int) -> int:
i = 2
cnt, s = 2, x + 1
while i <= x // i:
if x % i == 0:
cnt += 1
s += i
if i * i != x:
cnt += 1
s += x // i
i += 1
return s if cnt == 4 else 0
return sum(f(x) for x in nums)
Complexity
The time complexity is , where is the length of the array. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.