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)

šŸ› ļø 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

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit