#279

Perfect Squares

Medium
MathDynamic ProgrammingBreadth-First SearchDynamic ProgrammingBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n√n)
Space
O(1)
O(n)
💡

Intuition

Time O(n√n)Space O(n)

The optimal solution uses dynamic programming to build up the solution from smaller subproblems. It efficiently calculates the minimum number of perfect squares needed for each number up to n.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array dp where dp[i] represents the least number of perfect squares that sum to i.
  2. 2Step 2: Initialize dp[0] = 0 and fill dp[i] for all i from 1 to n using previously computed values.
  3. 3Step 3: For each i, iterate through all perfect squares less than or equal to i and update dp[i] accordingly.
solution.py10 lines
1# Full working Python code
2from math import isqrt
3
4def numSquares(n):
5    dp = [float('inf')] * (n + 1)
6    dp[0] = 0
7    for i in range(1, n + 1):
8        for j in range(1, isqrt(i) + 1):
9            dp[i] = min(dp[i], dp[i - j * j] + 1)
10    return dp[n]

Complexity note: The time complexity is O(n√n) because for each number up to n, we check all perfect squares up to that number, leading to a linear scan for each square.

  • 1Understanding perfect squares is crucial for solving this problem efficiently.
  • 2Dynamic programming allows us to build solutions incrementally, reducing redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.