AlgoMaster Logo

Perfect Squares

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force using Recursion

Intuition:

The simplest way to solve the problem is by trying all combinations. For a given number n, see if you can subtract a perfect square and solve the rest of the problem for n - perfect_square recursively.

Steps:

  1. Recursive function will be called reducing n by i*i, where i goes from 1 to sqrt(n).
  2. Base case: If n is 0, return 0 as we do not need any squares to sum up to 0.
  3. Return the minimum number of squares necessary.

Code:

2. Dynamic Programming

Intuition:

We can improve upon the recursive approach by storing results of subproblems (memoization). Use an array where dp[i] keeps track of the least number of perfect squares that sum up to i.

Steps:

  1. Initialize an array dp of size n + 1 where dp[0] = 0.
  2. Iterate over each number up to n and compute dp[i] by adding a perfect square j*j.
  3. For each idp[i] equals the min of dp[i] and dp[i - j*j] + 1.

Code:

3. Mathematical Approach using Lagrange's Four Square Theorem

Intuition:

Lagrange's Four Square Theorem states that any natural number is the sum of four integer squares at most. Using some mathematical deductions, especially checking for perfect squares can make the solution optimal.

Steps:

  1. Check if n is a perfect square.
  2. Applying a few checks based on the property of modulo 4 and perfect number subtraction.

Code: