Tutorialspoint
Problem
Solution
Submissions

Perfect Squares

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C# program to implement the NumSquares(int n) function that calculates 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:
    • Step 1: Identify all perfect squares less than or equal to n (1, 4, 9).
    • Step 2: Find the minimum number of these perfect squares needed to sum to n.
      • 12 = 4 + 4 + 4 (three perfect squares)
    • Step 3: Return the minimum count, which is 3.
Example 2
  • Input: n = 13
  • Output: 2
  • Explanation:
    • Step 1: Identify all perfect squares less than or equal to n (1, 4, 9).
    • Step 2: Find the minimum number of these perfect squares needed to sum to n.
      • 13 = 4 + 9 (two perfect squares)
    • Step 3: Return the minimum count, which is 2.
Constraints
  • 1 ≤ n ≤ 10^4
  • Time Complexity: O(n * sqrt(n)) where n is the input integer
  • Space Complexity: O(n) for the dynamic programming array
  • Your solution should work efficiently for all valid inputs
Dynamic Programming AlgorithmsAccentureApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider this as a shortest path problem and use BFS to solve it
  • Alternatively, use dynamic programming to build up the solution
  • For each number from 1 to n, find the minimum number of perfect squares needed
  • Use previously calculated results to compute the current number
  • Consider all possible perfect squares less than or equal to the current number

Steps to solve by this approach:

 Step 1: Create a dp array of size n+1 to store the minimum number of perfect squares needed for each number from 0 to n.
 Step 2: Initialize dp[0] = 0 as our base case (0 requires 0 perfect squares).
 Step 3: Initialize all other dp values to a very large number.
 Step 4: For each number i from 1 to n, consider all perfect squares less than or equal to i.
 Step 5: For each such perfect square j*j, update dp[i] = min(dp[i], dp[i - j*j] + 1).
 Step 6: The '+1' represents using one perfect square (j*j).
 Step 7: Return dp[n], which holds the minimum number of perfect squares that sum to n.

Submitted Code :