Find Shortest Square-Sum Path
PinduoduoSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to model a shortest-path graph search problem where states are integers and transitions involve adding perfect squares.
Problem Statement
Given a target integer n (1 <= n <= 10^5), find the minimum number of perfect square numbers that sum up to n. While many numbers can be represented as a sum of squares, you must determine the smallest count required to reach exactly n.
Implement the following function:
def min_square_sum(n: int) -> int:
pass
Examples
Example 1:
- Input:
n = 12 - Output:
3 - Explanation:
12 = 4 + 4 + 4(3 squares).
Example 2:
- Input:
n = 13 - Output:
2 - Explanation:
13 = 4 + 9(2 squares).
Constraints
1 <= n <= 10^5- Time complexity should be better than O(n * sqrt(n)).
Considerations
- Consider the edge cases where
nis already a perfect square. - Lagrange's Four-Square Theorem states that every natural number can be represented as the sum of four integer squares; use this to bound your search space.
Hints
Hint 1
This problem can be modeled as a shortest-path problem on a graph where nodes are numbers 0 to n and edges exist between `i` and `i + k^2`.
Hint 2
A Dynamic Programming approach where `dp[i]` represents the minimum squares for `i` works by iterating through all possible perfect squares `k^2 <= i`.
Hint 3
Legendre's three-square theorem provides a faster way to check if a number can be represented as a sum of three squares, which can optimize the search for the result.
Follow-up questions
- How would you reconstruct the actual squares used to form the sum?
- If we were restricted to using each perfect square at most once, how would the problem complexity change?
- What is the theoretical upper bound on the number of squares required for any integer, and how does that affect your algorithm?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.