Mark As Completed Discussion

One Pager Cheat Sheet

  • Perfect squares are numbers that result from squaring a whole number and can be used to find the fewest number of perfect squares that sum to a given number n, subject to the constraints of n being a nonzero positive integer less than or equal to 10000, and the expected time/space complexity being O(n*sqrt(n))/O(n), respectively.
  • A number is a perfect square when its square root is a whole number, such as the 1st to 10th perfect squares, which are 1, 4, 9, 16, 25, 36, 49, 64, 81, 100.
  • We need to iterate through all possible numbers and perform a logical step at each step to find the least number of perfect squares that sum up to a given number.
  • The for loop will check each number from 1 up to the given number to see if it is a perfect square and count is incremented by 1 for each perfect square found.
  • We can reduce our brute force solution to be more efficient by considering only perfect squares that are less than our target number, and iterating through these to sum them up to the target.
  • We can optimize the time complexity of finding the minimum number of perfect squares needed to add up to a certain sum by turning it into a shortest path problem, constructing a graph and memo-izing the calculations with a hash or an array.

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

You're doing a wonderful job. Keep going!

If you had any problems with this tutorial, check out the main forum thread here.