MEDIUM 1-D Dynamic Programming
279. Perfect Squares
š Problem
Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
š§ Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- ā¢Array methods (`push`, `pop`, `shift`, `slice`)
- ā¢Object/Map/Set usage patterns
- ā¢Function parameter and return typing
- ā¢Array DP table updates
- ā¢State transition thinking
- ā¢Base case initialization
Logical Thinking Concepts
- ā¢Define invariants before coding
- ā¢Check edge cases first (`[]`, single element, duplicates)
- ā¢Estimate time/space before implementation
- ā¢Apply Dynamic Programming reasoning pattern
š” Approach
- ā Use DP where dp[i] = min number of perfect squares summing to i
- ā For each i, check all squares j² <= i
- ā dp[i] = min(dp[i - j²] + 1) for all valid j
- ā Return dp[n]
- ā Time: O(nān), Space: O(n)
š§ Prerequisites
š ļø Hints & Pitfalls
Hints
- ā¢Use DP where dp[i] = min number of perfect squares summing to i
- ā¢For each i, check all squares j² <= i
- ā¢dp[i] = min(dp[i - j²] + 1) for all valid j
Common Pitfalls
- ā¢Return dp[n]
- ā¢Time: O(nān), Space: O(n)
š§Ŗ Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
numSquares(12); Expected:
3 Test Case 2
Not run Input:
numSquares(13); Expected:
2 Test Case 3
Not run Input:
numSquares(1); Expected:
1 š Code Editor
š¤ Output