Find Shortest Square-Sum Path
Company: Pinduoduo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving skills with number-theoretic reasoning about perfect squares and the ability to reconstruct a minimal-length additive sequence.
Constraints
- 1 <= n <= 10^4
- Each chosen value in the returned sequence must be a perfect square
- The sum of the returned sequence must be exactly n
Examples
Input: 1
Expected Output: [1]
Explanation: 1 is already a perfect square, so the shortest path uses one step.
Input: 2
Expected Output: [1, 1]
Explanation: The only way to reach 2 is 1 + 1, so the shortest sequence has length 2.
Input: 12
Expected Output: [4, 4, 4]
Explanation: 12 = 4 + 4 + 4, and it cannot be written as the sum of 1 or 2 perfect squares.
Input: 18
Expected Output: [9, 9]
Explanation: 18 = 9 + 9, so the shortest sequence has length 2.
Input: 48
Expected Output: [16, 16, 16]
Explanation: 48 = 16 + 16 + 16, and there is no way to express 48 as the sum of 1 or 2 perfect squares.
Input: 100
Expected Output: [100]
Explanation: 100 is itself a perfect square, so one step is enough.
Hints
- Think of each value from 0 to n as a node in a graph. From x, you can go to x + s for every perfect square s such that x + s <= n.
- Use BFS to guarantee the fewest number of steps, and store the previous total plus the square used so you can reconstruct the actual path.