279. Perfect Squares LeetCode Solution

In this guide, you will get 279. Perfect Squares LeetCode Solution with the best time and space complexity. The solution to Perfect Squares problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Perfect Squares solution in C++
  4. Perfect Squares solution in Java
  5. Perfect Squares solution in Python
  6. Additional Resources
279. Perfect Squares LeetCode Solution image

Problem Statement of Perfect Squares

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. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Constraints:

1 <= n <= 104

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(n\log n)

279. Perfect Squares LeetCode Solution in C++

class Solution {
 public:
  int numSquares(int n) {
    vector<int> dp(n + 1, n);  // 1^2 x n
    dp[0] = 0;                 // no way
    dp[1] = 1;                 // 1^2

    for (int i = 2; i <= n; ++i)
      for (int j = 1; j * j <= i; ++j)
        dp[i] = min(dp[i], dp[i - j * j] + 1);

    return dp[n];
  }
};
/* code provided by PROGIEZ */

279. Perfect Squares LeetCode Solution in Java

class Solution {
  public int numSquares(int n) {
    int[] dp = new int[n + 1];
    Arrays.fill(dp, n); // 1^2 x n
    dp[0] = 0;          // no way
    dp[1] = 1;          // 1^2

    for (int i = 2; i <= n; ++i)
      for (int j = 1; j * j <= i; ++j)
        dp[i] = Math.min(dp[i], dp[i - j * j] + 1);

    return dp[n];
  }
}
// code provided by PROGIEZ

279. Perfect Squares LeetCode Solution in Python

class Solution:
  def numSquares(self, n: int) -> int:
    dp = [n] * (n + 1)  # 1^2 x n
    dp[0] = 0  # no way
    dp[1] = 1  # 1^2

    for i in range(2, n + 1):
      j = 1
      while j * j <= i:
        dp[i] = min(dp[i], dp[i - j * j] + 1)
        j += 1

    return dp[n]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.