The Wayback Machine - https://web.archive.org/web/20240905134053/https://www.geeksforgeeks.org/minimum-number-of-squares-whose-sum-equals-to-given-number-n/
Open In App

Minimum perfect squares to add that sum to given number.

Last Updated : 05 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
45.22%
36.3K

A number can always be represented as a sum of squares of other numbers. Note that 1 is a square and we can always break a number as (1*1 + 1*1 + 1*1 + …). Given a number n, find the minimum number of squares that sum to X.

Examples : 

Input:  n = 100
Output: 1
Explanation:
100 can be written as 102. Note that 100 can also be written as 52 + 52 + 52 + 52, but this representation requires 4 squares.

Input:  n = 6
Output: 3

Recommended Practice

The idea is simple, we start from 1 and go to a number whose square is smaller than or equals n. For every number x, we recur for n-x. Below is the recursive formula. 

If n = 1 and x*x <= n

Below is a simple recursive solution based on the above recursive formula. 

C++




// A naive recursive C++
// program to find minimum
// number of squares whose sum
// is equal to a given number
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of minimum
// squares that sum to n
int getMinSquares(unsigned int n)
{
    // base cases
    // if n is perfect square then
    // Minimum squares required is 1
    // (144 = 12^2)
    if (sqrt(n) - floor(sqrt(n)) == 0)
        return 1;
    if (n <= 3)
        return n;
 
    // getMinSquares rest of the
    // table using recursive
    // formula
    // Maximum squares required
    // is n (1*1 + 1*1 + ..)
    int res = n;
 
    // Go through all smaller numbers
    // to recursively find minimum
    for (int x = 1; x <= n; x++)
    {
        int temp = x * x;
        if (temp > n)
            break;
        else
            res = min(res, 1 + getMinSquares
                                  (n - temp));
    }
    return res;
}
 
// Driver code
int main()
{
    cout << getMinSquares(6);
    return 0;
}


Java




// A naive recursive JAVA
// program to find minimum
// number of squares whose
// sum is equal to a given number
import java.util.*;
import java.io.*;
 
class squares
{
     
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
         
        // base cases
        if (n <= 3)
            return n;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
        // Maximum squares required is
        int res = n;
        // n (1*1 + 1*1 + ..)
 
        // Go through all smaller numbers
        // to recursively find minimum
        for (int x = 1; x <= n; x++)
        {
            int temp = x * x;
            if (temp > n)
                break;
            else
                res = Math.min(res, 1 +
                          getMinSquares(n - temp));
        }
        return res;
    }
   
    // Driver code
    public static void main(String args[])
    {
        System.out.println(getMinSquares(6));
    }
}
/* This code is contributed by Rajat Mishra */


Python3




# A naive recursive Python program to
# find minimum number of squares whose
# sum is equal to a given number
 
# Returns count of minimum squares
# that sum to n
def getMinSquares(n):
 
    # base cases
    if n <= 3:
        return n;
 
    # getMinSquares rest of the table
    # using recursive formula
    # Maximum squares required
    # is n (1 * 1 + 1 * 1 + ..)
    res = n
 
    # Go through all smaller numbers
    # to recursively find minimum
    for x in range(1, n + 1):
        temp = x * x;
        if temp > n:
            break
        else:
            res = min(res, 1 + getMinSquares(n
                                  - temp))
     
    return res;
 
# Driver code
print(getMinSquares(6))
 
# This code is contributed by nuclode


C#




// A naive recursive C# program
// to find minimum number of
// squares whose sum is equal
// to a given number
using System;
 
class GFG
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // base cases
        if (n <= 3)
            return n;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
 
        // Maximum squares required is
        // n (1*1 + 1*1 + ..)
        int res = n;
 
        // Go through all smaller numbers
        // to recursively find minimum
        for (int x = 1; x <= n; x++)
        {
            int temp = x * x;
            if (temp > n)
                break;
            else
                res = Math.Min(res, 1 +
                      getMinSquares(n - temp));
        }
        return res;
    }
 
    // Driver Code
    public static void Main()
    {
        Console.Write(getMinSquares(6));
    }
}
 
// This code is contributed by nitin mittal


Javascript




<script>
 
// A naive recursive Javascript program
// to find minimum number of squares
// whose sum is equal to a given number
 
// Returns count of minimum
// squares that sum to n
function getMinSquares(n)
{
     
    // base cases
    if (n <= 3)
        return n;
 
    // getMinSquares rest of the
    // table using recursive
    // formula
 
    // Maximum squares required is
    // n (1*1 + 1*1 + ..)
    let res = n;
 
    // Go through all smaller numbers
    // to recursively find minimum
    for(let x = 1; x <= n; x++)
    {
        let temp = x * x;
         
        if (temp > n)
            break;
        else
            res = Math.min(res,
            1 + getMinSquares(n - temp));
    }
    return res;
}
 
// Driver code
document.write(getMinSquares(6));
 
// This code is contributed by suresh07
 
</script>


PHP




<?php
// A naive recursive PHP program
// to find minimum number of
// squares whose sum is equal
// to a given number
 
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
    // base cases
    if ($n <= 3)
        return $n;
 
    // getMinSquares rest of the
    // table using recursive formula
     
    // Maximum squares required
    // is n (1*1 + 1*1 + ..)
    $res = $n;
 
    // Go through all smaller numbers
    // to recursively find minimum
    for ($x = 1; $x <= $n; $x++)
    {
        $temp = $x * $x;
        if ($temp > $n)
            break;
        else
            $res = min($res, 1 +
                       getMinSquares($n -
                                     $temp));
    }
    return $res;
}
 
// Driver Code
echo getMinSquares(6);
 
// This code is contributed
// by nitin mittal.
?>


Output

3

Time Complexity: O(2^n)

Space Complexity: O(n) where n is the recursion stack space.

The time complexity of the above solution is exponential. If we draw the recursion tree, we can observe that many subproblems are solved again and again. For example, when we start from n = 6, we can reach 4 by subtracting one 2 times and by subtracting 2 one times. So the subproblem for 4 is called twice.

Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So min square sum problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array table[][] in a bottom-up manner. Below is a Dynamic programming-based solution.

C++




// A dynamic programming based
// C++ program to find minimum
// number of squares whose sum
// is equal to a given number
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of minimum
// squares that sum to n
int getMinSquares(int n)
{
    // We need to check base case
    // for n i.e. 0,1,2
    // the below array creation
    // will go OutOfBounds.
    if(n<=3)
      return n;
     
    // Create a dynamic
    // programming table
    // to store sq
    int* dp = new int[n + 1];
 
    // getMinSquares table
    // for base case entries
    dp[0] = 0;
    dp[1] = 1;
    dp[2] = 2;
    dp[3] = 3;
 
    // getMinSquares rest of the
    // table using recursive
    // formula
    for (int i = 4; i <= n; i++)
    {
         
        // max value is i as i can
        // always be represented
        // as 1*1 + 1*1 + ...
        dp[i] = i;
 
        // Go through all smaller numbers to
        // to recursively find minimum
        for (int x = 1; x <= ceil(sqrt(i)); x++)
        {
            int temp = x * x;
            if (temp > i)
                break;
            else
                dp[i] = min(dp[i], 1 +
                                  dp[i - temp]);
        }
    }
 
    // Store result and free dp[]
    int res = dp[n];
    delete[] dp;
 
    return res;
}
 
// Driver code
int main()
{
    cout << getMinSquares(6);
    return 0;
}


Java




// A dynamic programming based
// JAVA program to find minimum
// number of squares whose sum
// is equal to a given number
import java.util.*;
import java.io.*;
 
class squares
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // We need to add a check
        // here for n. If user enters
        // 0 or 1 or 2
        // the below array creation
        // will go OutOfBounds.
        if (n <= 3)
            return n;
 
        // Create a dynamic programming
        // table
        // to store sq
        int dp[] = new int[n + 1];
 
        // getMinSquares table for
        // base case entries
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
        for (int i = 4; i <= n; i++)
        {
         
            // max value is i as i can
            // always be represented
            // as 1*1 + 1*1 + ...
            dp[i] = i;
 
            // Go through all smaller numbers to
            // to recursively find minimum
            for (int x = 1; x <= Math.ceil(
                              Math.sqrt(i)); x++)
            {
                int temp = x * x;
                if (temp > i)
                    break;
                else
                    dp[i] = Math.min(dp[i], 1
                                  + dp[i - temp]);
            }
        }
 
        // Store result and free dp[]
        int res = dp[n];
 
        return res;
    }
   
    // Driver Code
    public static void main(String args[])
    {
        System.out.println(getMinSquares(6));
    }
} /* This code is contributed by Rajat Mishra */


Python3




# A dynamic programming based Python
# program to find minimum number of
# squares whose sum is equal to a
# given number
from math import ceil, sqrt
 
# Returns count of minimum squares
# that sum to n
def getMinSquares(n):
 
    # Create a dynamic programming table
    # to store sq and getMinSquares table
    # for base case entries
    dp = [0, 1, 2, 3]
 
    # getMinSquares rest of the table
    # using recursive formula
    for i in range(4, n + 1):
         
        # max value is i as i can always
        # be represented as 1 * 1 + 1 * 1 + ...
        dp.append(i)
 
        # Go through all smaller numbers
        # to recursively find minimum
        for x in range(1, int(ceil(sqrt(i))) + 1):
            temp = x * x;
            if temp > i:
                break
            else:
                dp[i] = min(dp[i], 1 + dp[i-temp])
 
    # Store result
    return dp[n]
 
# Driver code
print(getMinSquares(6))
 
# This code is contributed by nuclode


C#




// A dynamic programming based
// C# program to find minimum
// number of squares whose sum
// is equal to a given number
using System;
 
class squares
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // We need to add a check here
        // for n. If user enters 0 or 1 or 2
        // the below array creation will go
        // OutOfBounds.
 
        if (n <= 3)
            return n;
 
        // Create a dynamic programming
        // table to store sq
        int[] dp = new int[n + 1];
 
        // getMinSquares table for base
        // case entries
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
 
        // getMinSquares for rest of the
        // table using recursive formula
        for (int i = 4; i <= n; i++)
        {
         
            // max value is i as i can
            // always be represented
            // as 1 * 1 + 1 * 1 + ...
            dp[i] = i;
 
            // Go through all smaller numbers to
            // to recursively find minimum
            for (int x = 1; x <= Math.Ceiling(
                              Math.Sqrt(i)); x++)
            {
                int temp = x * x;
                if (temp > i)
                    break;
                else
                    dp[i] = Math.Min(dp[i], 1 +
                                    dp[i - temp]);
            }
        }
 
        // Store result and free dp[]
        int res = dp[n];
 
        return res;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Console.Write(getMinSquares(6));
    }
}
 
// This code is contributed by Nitin Mittal.


Javascript




<script>
 
// A dynamic programming based
// javascript program to find minimum
// number of squares whose sum
// is equal to a given number
 
  
    // Returns count of minimum
    // squares that sum to n
    function getMinSquares( n)
    {
  
        // We need to add a check here
        // for n. If user enters 0 or 1 or 2
        // the below array creation will go
        // OutOfBounds.
  
        if (n <= 3)
            return n;
  
        // Create a dynamic programming
        // table to store sq
        var dp = new Array(n + 1);
  
        // getMinSquares table for base
        // case entries
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
  
        // getMinSquares for rest of the
        // table using recursive formula
        for (var i = 4; i <= n; i++)
        {
          
            // max value is i as i can
            // always be represented
            // as 1 * 1 + 1 * 1 + ...
            dp[i] = i;
  
            // Go through all smaller numbers to
            // to recursively find minimum
            for (var x = 1; x <= Math.ceil(
                              Math.sqrt(i)); x++)
            {
                var temp = x * x;
                if (temp > i)
                    break;
                else
                    dp[i] = Math.min(dp[i], 1 +
                                    dp[i - temp]);
            }
        }
  
        // Store result and free dp[]
        var res = dp[n];
  
        return res;
    }
  
    // Driver Code
 
        document.write(getMinSquares(6));
 
 
</script>


PHP




<?php
// A dynamic programming based
// PHP program to find minimum
// number of squares whose sum
// is equal to a given number
 
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
     
    // Create a dynamic programming
    // table to store sq
    $dp;
 
    // getMinSquares table for
    // base case entries
    $dp[0] = 0;
    $dp[1] = 1;
    $dp[2] = 2;
    $dp[3] = 3;
 
    // getMinSquares rest of the
    // table using recursive formula
    for ($i = 4; $i <= $n; $i++)
    {
        // max value is i as i can
        // always be represented
        // as 1*1 + 1*1 + ...
        $dp[$i] = $i;
 
        // Go through all smaller
        // numbers to recursively
        // find minimum
        for ($x = 1; $x <= ceil(sqrt($i));
                                     $x++)
        {
            $temp = $x * $x;
            if ($temp > $i)
                break;
            else $dp[$i] = min($dp[$i],
                       (1 + $dp[$i - $temp]));
        }
    }
 
    // Store result
    // and free dp[]
    $res = $dp[$n];
 
    // delete $dp;
    return $res;
}
 
// Driver Code
echo getMinSquares(6);
     
// This code is contributed
// by shiv_bhakt.
?>


Output

3

Time Complexity: O(n*sqrtn)
Auxiliary Space: O(n)

Thanks to Gaurav Ahirwar for suggesting this solution.

Another Approach: (USING MEMOIZATION)

The problem can be solved using the memoization method (dynamic programming) as well.

Below is the implementation:

C++




#include <bits/stdc++.h>
using namespace std;
 
int minCount(int n)
 
{
 
    int* minSquaresRequired = new int[n + 1];
 
    minSquaresRequired[0] = 0;
 
    minSquaresRequired[1] = 1;
 
    for (int i = 2; i <= n; ++i)
 
    {
 
        minSquaresRequired[i] = INT_MAX;
 
        for (int j = 1; i - (j * j) >= 0; ++j)
 
        {
 
            minSquaresRequired[i]
                = min(minSquaresRequired[i],
                      minSquaresRequired[i - (j * j)]);
        }
 
        minSquaresRequired[i] += 1;
    }
 
    int result = minSquaresRequired[n];
 
    delete[] minSquaresRequired;
 
    return result;
}
 
// Driver code
int main()
{
    cout << minCount(6);
    return 0;
}


Java




import java.util.*;
 
class GFG {
 
    static int minCount(int n)
 
    {
 
        int[] minSquaresRequired = new int[n + 1];
 
        minSquaresRequired[0] = 0;
 
        minSquaresRequired[1] = 1;
 
        for (int i = 2; i <= n; ++i)
 
        {
 
            minSquaresRequired[i] = Integer.MAX_VALUE;
 
            for (int j = 1; i - (j * j) >= 0; ++j)
 
            {
 
                minSquaresRequired[i] = Math.min(minSquaresRequired[i], minSquaresRequired[i - (j * j)]);
            }
 
            minSquaresRequired[i] += 1;
        }
 
        int result = minSquaresRequired[n];
 
        return result;
    }
 
    // Driver code
    public static void main(String[] args) {
        System.out.print(minCount(6));
    }
}
 
// This code contributed by gauravrajput1


Python3




import sys
def minCount(n):
    minSquaresRequired = [0 for i in range(n+1)];
 
    minSquaresRequired[0] = 0;
 
    minSquaresRequired[1] = 1;
 
    for i in range(2,n+1):
 
        minSquaresRequired[i] = sys.maxsize;
        j = 1
 
        for j in range(1,i - (j * j)):
            if(i - (j * j) >= 0):
                minSquaresRequired[i] = min(minSquaresRequired[i], minSquaresRequired[i - (j * j)]);
            else:
                break
         
 
        minSquaresRequired[i] += 1;
     
    result = minSquaresRequired[n];
 
    return result;
 
# Driver code
if __name__ == '__main__':
    print(minCount(6));
 
 
# This code is contributed by umadevi9616


C#




using System;
class GFG {
 
    static int minCount(int n)
    {
        int[] minSquaresRequired = new int[n + 1];
        minSquaresRequired[0] = 0;
        minSquaresRequired[1] = 1;
        for (int i = 2; i <= n; ++i)
 
        {
 
            minSquaresRequired[i] = Int32.MaxValue;
            for (int j = 1; i - (j * j) >= 0; ++j)
            {
                minSquaresRequired[i] = Math.Min(minSquaresRequired[i], minSquaresRequired[i - (j * j)]);
            }
            minSquaresRequired[i] += 1;
        }
        int result = minSquaresRequired[n];
        return result;
    }
 
    // Driver code
    public static void Main(String[] args) {
        Console.Write(minCount(6));
    }
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
        function minCount(n)
        {
 
            let minSquaresRequired = new Array(n + 1);
 
            minSquaresRequired[0] = 0;
 
            minSquaresRequired[1] = 1;
 
            for (let i = 2; i <= n; ++i) {
 
                minSquaresRequired[i] = Number.MAX_VALUE;
 
                for (let j = 1; i - (j * j) >= 0; ++j) {
 
                    minSquaresRequired[i]
                        = Math.min(minSquaresRequired[i],
                            minSquaresRequired[i - (j * j)]);
                }
 
                minSquaresRequired[i] += 1;
            }
 
            let result = minSquaresRequired[n];
            return result;
        }
 
        // Driver code
        document.write(minCount(6));
 
// This code is contributed by Potta Lokesh
    </script>


Output

3

Another Approach:
This problem can also be solved by using graphs. Here is the basic idea of how it can be done. 
We will use BFS (Breadth-First Search) to find the minimum number of steps from a given value of n to 0. 
So, for every node, we will push the next possible valid path which is not visited yet into a queue and, 
and if it reaches node 0, we will update our answer if it is less than the answer. 

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum
// squares that sum to n
int numSquares(int n)
{
  
  // Creating visited vector
  // of size n + 1
  vector<int> visited(n + 1,0);
   
  // Queue of pair to store node
  // and number of steps
  queue< pair<int,int> >q;
   
  // Initially ans variable is
  // initialized with inf
  int ans = INT_MAX;
   
  // Push starting node with 0
  // 0 indicate current number
  // of step to reach n
  q.push({n,0});
   
  // Mark starting node visited
  visited[n] = 1;
  while(!q.empty())
  {
    pair<int,int> p;
    p = q.front();
    q.pop();
 
    // If node reaches its destination
    // 0 update it with answer
    if(p.first == 0)
      ans=min(ans, p.second);
 
    // Loop for all possible path from
    // 1 to i*i <= current node(p.first)
    for(int i = 1; i * i <= p.first; i++)
    {
       
      // If we are standing at some node
      // then next node it can jump to will
      // be current node-
      // (some square less than or equal n)
      int path=(p.first - (i*i));
 
      // Check if it is valid and
      // not visited yet
      if(path >= 0 && ( !visited[path]
                             || path == 0))
      {
         
        // Mark visited
        visited[path]=1;
         
        // Push it it Queue
        q.push({path,p.second + 1});
      }
    }
  }
   
  // Return ans to calling function
  return ans;
}
 
// Driver code
int main()
{
  cout << numSquares(12);
  return 0;
}


Java




// Java program for the above approach
import java.util.*;
import java.awt.Point;
class GFG
{
  // Function to count minimum
  // squares that sum to n
  public static int numSquares(int n)
  {
 
    // Creating visited vector
    // of size n + 1
    int visited[] = new int[n + 1];
 
    // Queue of pair to store node
    // and number of steps
    Queue<Point> q = new LinkedList<>();
 
    // Initially ans variable is
    // initialized with inf
    int ans = Integer.MAX_VALUE;
 
    // Push starting node with 0
    // 0 indicate current number
    // of step to reach n
    q.add(new Point(n, 0));
 
    // Mark starting node visited
    visited[n] = 1;
    while(q.size() != 0)
    {
      Point p = q.peek();
      q.poll();
 
      // If node reaches its destination
      // 0 update it with answer
      if(p.x == 0)
        ans = Math.min(ans, p.y);
 
      // Loop for all possible path from
      // 1 to i*i <= current node(p.first)
      for(int i = 1; i * i <= p.x; i++)
      {
 
        // If we are standing at some node
        // then next node it can jump to will
        // be current node-
        // (some square less than or equal n)
        int path = (p.x - (i * i));
 
        // Check if it is valid and
        // not visited yet
        if(path >= 0 && (visited[path] == 0 || path == 0))
        {
 
          // Mark visited
          visited[path] = 1;
 
          // Push it it Queue
          q.add(new Point(path, p.y + 1));
        }
      }
    }
 
    // Return ans to calling function
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    System.out.println(numSquares(12));
  }
}
 
// This code is contributed by divyesh072019


Python3




# Python3 program for the above approach
import sys
 
# Function to count minimum
# squares that sum to n
def numSquares(n) :
 
    # Creating visited vector
    # of size n + 1
    visited = [0]*(n + 1)
     
    # Queue of pair to store node
    # and number of steps
    q = []
     
    # Initially ans variable is
    # initialized with inf
    ans = sys.maxsize
     
    # Push starting node with 0
    # 0 indicate current number
    # of step to reach n
    q.append([n, 0])
     
    # Mark starting node visited
    visited[n] = 1
    while(len(q) > 0) :
         
        p = q[0]
        q.pop(0)
     
        # If node reaches its destination
        # 0 update it with answer
        if(p[0] == 0) :
            ans = min(ans, p[1])
     
        # Loop for all possible path from
        # 1 to i*i <= current node(p.first)
        i = 1
        while i * i <= p[0] :
           
            # If we are standing at some node
            # then next node it can jump to will
            # be current node-
            # (some square less than or equal n)
            path = p[0] - i * i
         
            # Check if it is valid and
            # not visited yet
            if path >= 0 and (visited[path] == 0 or path == 0) :
             
                # Mark visited
                visited[path] = 1 
                 
                # Push it it Queue
                q.append([path,p[1] + 1])
             
            i += 1
     
    # Return ans to calling function
    return ans
 
print(numSquares(12))
 
# This code is contributed by divyeshrabadiya07


C#




// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
   
public class Point
{
    public int x, y;
     
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
// Function to count minimum
// squares that sum to n
public static int numSquares(int n)
{
     
    // Creating visited vector
    // of size n + 1
    int []visited = new int[n + 1];
     
    // Queue of pair to store node
    // and number of steps
    Queue q = new Queue();
     
    // Initially ans variable is
    // initialized with inf
    int ans = 1000000000;
     
    // Push starting node with 0
    // 0 indicate current number
    // of step to reach n
    q.Enqueue(new Point(n, 0));
     
    // Mark starting node visited
    visited[n] = 1;
     
    while(q.Count != 0)
    {
        Point p = (Point)q.Dequeue();
         
        // If node reaches its destination
        // 0 update it with answer
        if (p.x == 0)
            ans = Math.Min(ans, p.y);
         
        // Loop for all possible path from
        // 1 to i*i <= current node(p.first)
        for(int i = 1; i * i <= p.x; i++)
        {
             
            // If we are standing at some node
            // then next node it can jump to will
            // be current node-
            // (some square less than or equal n)
            int path = (p.x - (i * i));
             
            // Check if it is valid and
            // not visited yet
            if (path >= 0 && (visited[path] == 0 ||
                                       path == 0))
            {
                 
                // Mark visited
                visited[path] = 1;
                 
                // Push it it Queue
                q.Enqueue(new Point(path, p.y + 1));
            }
        }
    }
     
    // Return ans to calling function
    return ans;
}
 
// Driver code
public static void Main(string[] args)
{
    Console.Write(numSquares(12));
}
}
 
// This code is contributed by rutvik_56


Javascript




// JavaScript program for the above approach
 
 
// Function to count minimum
// squares that sum to n
function numSquares(n)
{
    // Creating visited vector
    // of size n + 1
    let visited = new Array(n + 1).fill(0);
     
    // Queue of pair to store node
    // and number of steps
    let q = [];
     
    // Initially ans variable is
    // initialized with inf
    let ans = Number.MAX_SAFE_INTEGER;
     
    // Push starting node with 0
    // 0 indicate current number
    // of step to reach n
    q.push([n, 0]);
     
    // Mark starting node visited
    visited[n] = 1;
    while(q.length > 0)
    {
        let p = q[0];
        q.shift();
     
        // If node reaches its destination
        // 0 update it with answer
        if(p[0] == 0)
            ans = Math.min(ans, p[1]);
     
        // Loop for all possible path from
        // 1 to i*i <= current node(p.first)
        let i = 1;
        while (i * i <= p[0])
        {
            // If we are standing at some node
            // then next node it can jump to will
            // be current node-
            // (some square less than or equal n)
            let path = p[0] - i * i;
         
            // Check if it is valid and
            // not visited yet
            if (path >= 0  && (visited[path] == 0 || path == 0) )
            {
                // Mark visited
                visited[path] = 1;
                 
                // Push it it Queue
                q.push([path,p[1] + 1]);
            }           
            i += 1;
        }
    }
     
    // Return ans to calling function
    return ans;
}
 
console.log(numSquares(12));
 
// This code is contributed by phasing17


Output

3

The time complexity of the above problem is O(n)*sqrt(n) which is better than the Recursive approach. 
Also, it is a great way to understand how BFS (Breadth-First Search) works.

Please write a if you find anything incorrect, or you want to share more information about the topic discussed above.

Another Approach:

This problem can also be solved using Dynamic programming (Bottom-up approach). The idea is like coin change 2 (in which we need to tell minimum number of coins to make an amount from given coins[] array), here an array of all perfect squares less than or equal to n can be replaced by coins[] array and amount can be replaced by n. Just see this as an unbounded knapsack problem, Let’s see an example:

For given input n = 6, we will make an array upto 4,  arr : [1,4]

Here, answer will be (4 + 1 + 1 = 6) i.e. 3. 

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum
// squares that sum to n
int numSquares(int n)
{
    //Making the array of perfect squares less than or equal to n
    vector <int> arr;
    int i = 1;
    while(i*i <= n){
        arr.push_back(i*i);
        i++;
    }
    //A dp array which will store minimum number of perfect squares
    //required to make n from i at i th index
    vector <int> dp(n+1, INT_MAX);
    dp[n] = 0;
    for(int i = n-1; i>=0; i--){
        //checking from i th value to n value minimum perfect squares required
        for(int j = 0; j<arr.size(); j++){
            //check if index doesn't goes out of bound
            if(i + arr[j] <= n){
                dp[i] = min(dp[i], dp[i+arr[j]]);
            }
 
        }
        //from current to go to min step one i we need to take one step
        dp[i]++;
    }
    return dp[0];
     
}
 
// Driver code
int main()
{
    cout << numSquares(12);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to count minimum
// squares that sum to n
static int numSquares(int n)
{
   
    // Making the array of perfect squares less than or equal to n
    Vector <Integer> arr = new Vector<>();
    int k = 1;
    while(k * k <= n){
        arr.add(k * k);
        k++;
    }
   
    // A dp array which will store minimum number of perfect squares
    // required to make n from i at i th index
   int []dp = new int[n + 1];
   Arrays.fill(dp, Integer.MAX_VALUE);
    dp[n] = 0;
    for(int i = n - 1; i >= 0; i--)
    {
       
        // checking from i th value to n value minimum perfect squares required
        for(int j = 0; j < arr.size(); j++)
        {
           
            // check if index doesn't goes out of bound
            if(i + arr.elementAt(j) <= n)
            {
                dp[i] = Math.min(dp[i], dp[i+arr.elementAt(j)]);
            }
        }
       
        // from current to go to min step one i we need to take one step
        dp[i]++;
    }
    return dp[0];
}
 
// Driver code
public static void main(String[] args)
{
    System.out.print(numSquares(12));
}
}
 
// This code is contributed by umadevi9616.


Python3




# Python program for the above approach
import sys
 
# Function to count minimum
# squares that sum to n
def numSquares(n):
 
    # Making the array of perfect squares less than or equal to n
    arr = [];
    k = 1;
    while (k * k <= n):
        arr.append(k * k);
        k += 1;
     
 
    # A dp array which will store minimum number of perfect squares
    # required to make n from i at i th index
    dp = [sys.maxsize for i in range(n+1)];
     
    dp[n] = 0;
    for i in range(n-1, -1,-1):
 
        # checking from i th value to n value minimum perfect squares required
        for j in range(len(arr)):
 
            # check if index doesn't goes out of bound
            if (i + arr[j] <= n):
                dp[i] = min(dp[i], dp[i + arr[j]]);
             
        # from current to go to min step one i we need to take one step
        dp[i] += 1;
     
    return dp[0];
 
# Driver code
if __name__ == '__main__':
    print(numSquares(12));
 
# This code is contributed by gauravrajput1


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
// Function to count minimum
// squares that sum to n
static int numSquares(int n)
{
   
    // Making the array of perfect squares less than or equal to n
    List <int> arr = new List<int>();
    int k = 1;
    while(k * k <= n){
        arr.Add(k * k);
        k++;
    }
   
    // A dp array which will store minimum number of perfect squares
    // required to make n from i at i th index
   int []dp = new int[n + 1];
    for(int i = 0; i < n + 1; i++)
        dp[i] = int.MaxValue;
 
    dp[n] = 0;
    for(int i = n - 1; i >= 0; i--)
    {
       
        // checking from i th value to n value minimum perfect squares required
        for(int j = 0; j < arr.Count; j++)
        {
           
            // check if index doesn't goes out of bound
            if(i + arr[j] <= n)
            {
                dp[i] = Math.Min(dp[i], dp[i+arr[j]]);
            }
        }
       
        // from current to go to min step one i we need to take one step
        dp[i]++;
    }
    return dp[0];
}
 
// Driver code
public static void Main(String[] args)
{
    Console.Write(numSquares(12));
}
}
 
// This code is contributed by umadevi9616


Javascript




<script>
// javascript program for the above approach
 
    // Function to count minimum
    // squares that sum to n
    function numSquares(n) {
 
        // Making the array of perfect squares less than or equal to n
        var arr = new Array();
        var k = 1;
        while (k * k <= n) {
            arr.push(k * k);
            k++;
        }
 
        // A dp array which will store minimum number of perfect squares
        // required to make n from i at i th index
        var dp = Array(n + 1).fill(Number.MAX_VALUE);
         
        dp[n] = 0;
        for (i = n - 1; i >= 0; i--) {
 
            // checking from i th value to n value minimum perfect squares required
            for (j = 0; j < arr.length; j++) {
 
                // check if index doesn't goes out of bound
                if (i + arr[j] <= n) {
                    dp[i] = Math.min(dp[i], dp[i + arr[j]]);
                }
            }
 
            // from current to go to min step one i we need to take one step
            dp[i]++;
        }
        return dp[0];
    }
 
    // Driver code
     
        document.write(numSquares(12));
 
// This code is contributed by umadevi9616
</script>


Output

3

The time complexity of the above problem is O(n)*sqrt(n) as array will be made in sqrt(n) time and for loops for filling dp array will take n*sqrt(n) time atmost. The size of dp array will be n, so space complexity of this approach is O(n).

Another Approach: (Using Mathematics)

The solution is based on Lagrange’s Four Square Theorem.
According to the theorem, there can be atmost 4 solutions to the problem, i.e. 1, 2, 3, 4

Case 1:

Ans = 1 => This can happen if the number is a square number. 
n = {a2 : a ∈ W}
Example : 1, 4, 9, etc.

Case 2:

Ans = 2 => This is possible if the number is the sum of 2 square numbers.

n = {a2 + b2 : a, b ∈  W}  
Example : 2, 5, 18, etc. 

Case 3:

Ans = 3 => This can happen if the number is not of the form 4k(8m + 7).

For more information on this : https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem

n = {a2 + b2 + c2 : a, b, c ∈  W} ⟷  n ≢ {4k(8m + 7) : k, m ∈ W }
Example : 6, 11, 12 etc.

Case 4:

Ans = 4 => This can happen if the number is of the form 4k(8m + 7).

n = {a2 + b2 + c2 + d2 : a, b, c, d ∈  W} ⟷  n ≡  {4k(8m + 7) : k, m ∈ W }
Example : 7, 15, 23 etc.

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// returns true if the input number x is a square number,
// else returns false
bool isSquare(int x)
{
    int sqRoot = sqrt(x);
    return (sqRoot * sqRoot == x);
}
 
// Function to count minimum squares that sum to n
int cntSquares(int n)
{
    // ans = 1 if the number is a perfect square
    if (isSquare(n)) {
        return 1;
    }
 
    // ans = 2:
    // we check for each i if n - (i * i) is a perfect
    // square
    for (int i = 1; i <= (int)sqrt(n)+1; i++) {
        if (isSquare(n - (i * i))) {
            return 2;
        }
    }
 
    // ans = 4
    // possible if the number is representable in the form
    // 4^a (8*b + 7).
    while (n % 4 == 0) {
        n >>= 2;
    }
    if (n % 8 == 7) {
        return 4;
    }
 
    // since all the other cases have been evaluated, the
    // answer can only then be 3 if the program reaches here
    return 3;
}
 
// Driver Code
int main()
{
    cout << cntSquares(12) << endl;
    return 0;
}


Java




// Java code for the above approach
import java.util.*;
 
class GFG{
 
// returns true if the input number x is a square number,
// else returns false
static boolean isSquare(int x)
{
    int sqRoot = (int)Math.sqrt(x);
    return (sqRoot * sqRoot == x);
}
 
// Function to count minimum squares that sum to n
static int cntSquares(int n)
{
    // ans = 1 if the number is a perfect square
    if (isSquare(n)) {
        return 1;
    }
 
    // ans = 2:
    // we check for each i if n - (i * i) is a perfect
    // square
    for (int i = 1; i <= (int)Math.sqrt(n)+1; i++) {
        if (isSquare(n - (i * i))) {
            return 2;
        }
    }
 
    // ans = 4
    // possible if the number is representable in the form
    // 4^a (8*b + 7).
    while (n % 4 == 0) {
        n >>= 2;
    }
    if (n % 8 == 7) {
        return 4;
    }
 
    // since all the other cases have been evaluated, the
    // answer can only then be 3 if the program reaches here
    return 3;
}
 
// Driver Code
public static void main(String[] args)
{
    System.out.print(cntSquares(12) +"\n");
}
}
 
// This code is contributed by umadevi9616


Python3




# Python code for the above approach
import math
 
# returns True if the input number x is a square number,
# else returns False
def isSquare(x):
    sqRoot = int(math.sqrt(x));
    return (sqRoot * sqRoot == x);
 
# Function to count minimum squares that sum to n
def cntSquares(n):
   
    # ans = 1 if the number is a perfect square
    if (isSquare(n)):
        return 1;
     
    # ans = 2:
    # we check for each i if n - (i * i) is a perfect
    # square
    for i in range(1, int(math.sqrt(n))+1):
        if (isSquare(n - (i * i))):
            return 2;
         
    # ans = 4
    # possible if the number is representable in the form
    # 4^a (8*b + 7).
    while (n % 4 == 0):
        n >>= 2;
     
    if (n % 8 == 7):
        return 4;
     
    # since all the other cases have been evaluated, the
    # answer can only then be 3 if the program reaches here
    return 3;
 
# Driver Code
if __name__ == '__main__':
    print(cntSquares(12) , "");
 
# This code is contributed by gauravrajput1


C#




// C# code for the above approach
using System;
 
public class GFG{
 
// returns true if the input number x is a square number,
// else returns false
static bool isSquare(int x)
{
    int sqRoot = (int)Math.Sqrt(x);
    return (sqRoot * sqRoot == x);
}
 
// Function to count minimum squares that sum to n
static int cntSquares(int n)
{
    // ans = 1 if the number is a perfect square
    if (isSquare(n)) {
        return 1;
    }
 
    // ans = 2:
    // we check for each i if n - (i * i) is a perfect
    // square
    for (int i = 1; i <= (int)Math.Sqrt(n)+1; i++) {
        if (isSquare(n - (i * i))) {
            return 2;
        }
    }
 
    // ans = 4
    // possible if the number is representable in the form
    // 4^a (8*b + 7).
    while (n % 4 == 0) {
        n >>= 2;
    }
    if (n % 8 == 7) {
        return 4;
    }
 
    // since all the other cases have been evaluated, the
    // answer can only then be 3 if the program reaches here
    return 3;
}
 
// Driver Code
public static void Main(String[] args)
{
    Console.Write(cntSquares(12) +"\n");
}
}
 
// This code contributed by umadevi9616


Javascript




<script>
// javascript code for the above approach
 
    // returns true if the input number x is a square number,
    // else returns false
    function isSquare(x) {
        var sqRoot = parseInt( Math.sqrt(x));
        return (sqRoot * sqRoot == x);
    }
 
    // Function to count minimum squares that sum to n
    function cntSquares(n)
    {
     
        // ans = 1 if the number is a perfect square
        if (isSquare(n)) {
            return 1;
        }
 
        // ans = 2:
        // we check for each i if n - (i * i) is a perfect
        // square
        for (var i = 1; i <= parseInt( Math.sqrt(n))+1; i++) {
            if (isSquare(n - (i * i))) {
                return 2;
            }
        }
 
        // ans = 4
        // possible if the number is representable in the form
        // 4^a (8*b + 7).
        while (n % 4 == 0) {
            n >>= 2;
        }
        if (n % 8 == 7) {
            return 4;
        }
 
        // since all the other cases have been evaluated, the
        // answer can only then be 3 if the program reaches here
        return 3;
    }
 
    // Driver Code
        document.write(cntSquares(12) + "\n");
 
// This code is contributed by umadevi9616
</script>


Output

3

Time Complexity: O(sqrtn)
Auxiliary Space: O(1)



Similar Reads

Sum of distances between the two nearest perfect squares to all the nodes of the given linked list
Given a linked list, the task is to find the sum of distances between the two nearest perfect squares for all the nodes of the given linked list.Examples: Input: 3 -&gt; 15 -&gt; 7 -&gt; NULL Output: 15 For 3: closest left perfect square is 1 and closest right 4 i.e. 4-1 = 3 For 15: 16 - 9 = 7 For 7: 9 - 4 = 5 3 + 7 + 5 = 15 Input: 1 -&gt; 5 -&gt;
7 min read
Count of primes in a given range that can be expressed as sum of perfect squares
Given two integers L and R, the task is to find the number of prime numbers in the range [L, R] that can be represented by the sum of two squares of two numbers.Examples: Input: L = 1, R = 5 Output: 1 Explanation: Only prime number that can be expressed as sum of two perfect squares in the given range is 5 (22 + 12)Input: L = 7, R = 42 Output: 5 Ex
7 min read
Count ways to represent a number as sum of perfect squares
Given an integer N, the task is to find the number of ways to represent the number N as sum of perfect squares. Examples: Input: N = 9Output: 4Explanation:There are four ways to represent 9 as the sum of perfect squares:1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 91 + 1 + 1 + 1 + 1 + 4 = 91 + 4 + 4 = 99 = 9 Input: N = 8Output: 3 Naive Approach: The idea is
13 min read
Number of perfect squares between two given numbers
Given two given numbers a and b where 1&lt;=a&lt;=b, find the number of perfect squares between a and b (a and b inclusive).Examples Input : a = 3, b = 8 Output : 1 The only perfect square in given range is 4. Input : a = 9, b = 25 Output : 3 The three perfect squares in given range are 9, 16 and 25Recommended PracticePerfect Squares in a RangeTry
6 min read
Print all Perfect Numbers from an array whose sum of digits is also a Perfect Number
Given an array arr[] of size N, the task is to print all the perfect numbers from an array whose sum of digits is also a perfect number. Examples: Input: arr[] = { 3, 8, 12, 28, 6 }Output: 6Explanation: The array element arr[4] (= 6) is a perfect number. The array element arr[3] (= 28) is a perfect number but its sum of digits (= 10) is not a perfe
8 min read
Minimum number of squares whose sum equals to given number N | set 2
A number can always be represented as a sum of squares of other numbers. Note that 1 is a square, and we can always break a number as (1*1 + 1*1 + 1*1 + …). Given a number N, the task is to represent N as the sum of minimum square numbers. Examples: Input : 10 Output : 1 + 9 These are all possible ways 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 1 + 1 +
8 min read
Minimum number of squares whose sum equals to a given number N | Set-3
A number can always be represented as a sum of squares of other numbers. Note that 1 is a square, and we can always break a number as (1*1 + 1*1 + 1*1 + …). Given a number n, find the minimum number of squares that sum to N. Examples: Input: N = 13 Output: 2 Explanation: 13 can be expressed as, 13 = 32 + 22. Hence, the output is 2. Input: N = 100 O
7 min read
Find smallest perfect square number A such that N + A is also a perfect square number
Given a positive number N. The task is to find out the smallest perfect square number A such that N + A is also a perfect square number or return -1.Examples: Input: N = 3 Output: 1 Explanation: As 1 + 3 = 4 = 22 Input: N=1 Output: -1 Naive Approach: Traverse M from {1, 2, 3, 4, 5...} and check whether (N + M * M) is a perfect square number or not.
9 min read
Check if the sum of perfect squares in an array is divisible by x
Given an array arr[] and an integer x, the task is to check whether the sum of all the perfect squares from the array is divisible by x or not. If divisible then print Yes else print No. Examples: Input: arr[] = {2, 3, 4, 6, 9, 10}, x = 13 Output: Yes 4 and 9 are the only perfect squares from the array sum = 4 + 9 = 13 (which is divisible by 13) In
6 min read
Sum of all Perfect Squares lying in the range [L, R] for Q queries
Given Q queries in the form of 2D array arr[][] whose every row consists of two numbers L and R which signifies the range [L, R], the task is to find the sum of all perfect squares lying in this range. Examples: Input: Q = 2, arr[][] = {{4, 9}, {4, 16}} Output: 13 29 Explanation: From 4 to 9: only 4 and 9 are perfect squares. Therefore, 4 + 9 = 13.
7 min read
Find all combinations of perfect squares that sum up to N with duplicates
Given a positive integer N, the task is to print all possible sum of perfect squares such that the total sum of all perfect squares is equal to N. Example: Input: N=8Output: 4 4 1 1 1 1 4 1 1 1 1 1 1 1 1 Explanation: There are three possible ways to make sum equal to N Input: N=3Output: 1 1 1 Approach: The given problem can be solved using recursio
7 min read
Find sum of all odd perfect squares in the range [L, R]
Given two integers L and R. The task is to find the sum of all the odd numbers which are perfect square in the range [L, R]. Examples: Input: L = 1, R = 9Output: 10Explanation: The odd Numbers in the range are 1, 3, 5, 7, 9 and only 1, 9 are perfect squares of 1, 3. So, 1 + 9 = 10. Input: L = 50, R = 10,000Output: 166566 Naive Approach: The basic i
8 min read
Print all perfect squares from the given range
Given a range [L, R], the task is to print all the perfect squares from the given range.Examples: Input: L = 2, R = 24 Output: 4 9 16Input: L = 1, R = 100 Output: 1 4 9 16 25 36 49 64 81 100 Naive approach: Starting from L to R check whether the current element is a perfect square or not. If yes then print it.Below is the implementation of the abov
8 min read
Count of perfect squares of given length
Given an integer N, the task is to find the number of perfect squares of length N.Examples: Input: N = 1 Output: 3 Explanation: The single digit perfect squares are 1, 4 and 9. Input: N = 2 Output: 6 Explanation: The two-digit perfect squares are 16, 25, 36, 49, 64 and 81. Naive Approach: In order to solve this problem, we can check all the numbers
7 min read
Count array elements whose perfect squares are present in the given array
Given an array arr[], the task is to find the count of array elements whose squares are already present in the array. Examples: Input: arr[] = {2, 4, 5, 20, 16}Output: 2Explanation:{2, 4} has their squares {4, 16} present in the array. Input: arr[] = {1, 30, 3, 8, 64}Output: 2Explanation:{1, 8} has their squares {1, 64} present in the array. Naive
9 min read
Count number less than N which are product of perfect squares
Given an Integer N. The task is to count numbers P less than N such that P is a product of two distinct perfect squares. Examples: Input : N = 36 Output : 5 Numbers are 4 = 12 * 22, 9 = 12 * 32, 16 = 12 * 42, 25 = 12 * 52, 36 = 12 * 62Input : N = 1000000 Output : 999 Approach: Let us consider a number P = (a2 * b2) such that P &lt;= N. So we have (
3 min read
Largest number from the longest set of anagrams possible from all perfect squares of length K
Given an integer K such that there is a set of all possible perfect squares, each of length K. From this set of perfect squares, form a set of the longest possible length having those numbers which are anagram to each other. The task is to print the largest element present in the generated set of anagrams. Note: If there is more than one set of max
9 min read
Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Largest sub-array whose all elements are perfect squares
Given an array [Tex]arr [/Tex]of integer elements, the task is to find the length of the largest sub-array of [Tex]arr [/Tex]such that all the elements of the sub-array are perfect squares. Examples: Input: arr[] = {1, 7, 36, 4, 49, 2, 4} Output: 3 Maximum length sub-array with all elements as perfect squares is {36, 4, 49} Input: arr[] = {25, 100,
6 min read
Sort perfect squares in an array at their relative positions
Given an integer array [Tex]arr [/Tex], the task is to sort only the elements which are perfect squares at their relative positions in the array (positions of other elements must not be affected). Examples: Input: arr[] = {2, 64, 9, 8, 1, 4} Output: 2 1 4 8 9 64 1, 4, 9 and 64 are the only perfect squares from the array. Input: arr[] = {1, 49, 2, 3
7 min read
Smallest and Largest N-digit perfect squares
Given an integer N, the task is to find the smallest and the largest N digit numbers which are also perfect squares.Examples: Input: N = 2 Output: 16 81 16 and 18 are the smallest and the largest 2-digit perfect squares.Input: N = 3 Output: 100 961 Approach: For increasing values of N starting from N = 1, the series will go on like 9, 81, 961, 9801
3 min read
Count elements in an Array that can be represented as difference of two perfect squares
Given an array arr[], the task is to count the number of elements in the array that can be represented as in the form of the difference of two perfect square numbers. [Tex]a^2 - b^2 [/Tex]Examples: Input: arr[] = {1, 2, 3} Output: 2 Explanation: There are two such elements that can be represented as difference of square of two numbers - Element 1 -
5 min read
Subsets of size K with product equal to difference of two perfect squares
Given a distinct integers array arr[] of size N and an integer K, the task is to count the number of subsets of size K of array whose product of elements can be represented as a2 - b2. Examples: Input: arr[] = {1, 2, 3} K = 2 Output: 2 Explanation: All possible subsets of length 2 with their products are given below: {1, 2} = 2 {2, 3} = 6 {1, 3} =
6 min read
Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order
Given an array arr[] of size N (1 ? N ? 105), the task is to sort digits of each array element in descending order and replace each array element with the nearest perfect square and then print the array in ascending order. Examples: Input: arr[ ] = {29, 43, 28, 12}Output: 25 49 81 100Explanation:Sorting digits of each array element in descending or
7 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Nearest power of 2 of nearest perfect squares of non-repeating array elements
Given an array arr[] consisting of N positive integers, the task is to find the nearest perfect power of 2 of the nearest perfect squares of unique array elements. If the array does not contain any unique element, then print -1. Examples: Input: arr[] = {4, 11, 4, 3, 4}Output: 4 8Explanation:The unique elements in the given array are 11 and 3.The n
9 min read
Find the nearest odd and even perfect squares of odd and even array elements respectively
Given an array arr[ ] of size N, the task for each array element is to print the nearest perfect square having same parity. Examples: Input: arr[ ] = {6, 3, 2, 15}Output: 4 1 4 9Explanation:The nearest even perfect square of arr[0] (= 6) is 4.The nearest odd perfect square of arr[1] (= 3) is 1.The nearest even perfect square of arr[2] (= 2) is 4The
5 min read
Find pair of consecutive Perfect Squares with difference K
Given an integer K, the task is to find two consecutive perfect squares whose difference is K. If there don't exist any such pairs of numbers, then print -1. Examples: Input: K = 5Output: 4 9Explanation:So, 4 and 9 are the two perfect squares which differ by 5(= 9 - 4 = 5). Input: K = 4Output: -1 Naive Approach: The simple approach to solve the giv
4 min read
XOR of all Array elements that are perfect squares
Given an array arr[] containing N integers, the task is to find the XOR of all the elements of this array that are perfect squares. Examples: Input: arr[] = {3, 9, 16, 12, 13, 15} Output: 25Explanation: Only 9, 16 are the perfect squares in the given array.So the XOR of 9 and 16 is 25, XOR = 9 ^ 16 = 25 Input: arr[] = { 3, 9, 12, 13, 15 } Output: 9
5 min read
Sum of all subsets whose sum is a Perfect Number from a given array
Given an array arr[] consisting of N integers, the task is to find the sum of all subsets from an array, whose sum is a Perfect Number. Examples: Input: arr[] = {5, 4, 6}Output: 6Explanation:All possible subsets from the array arr[] are:{5} ? Sum = 5{4} ? Sum = 4.{6} ? Sum = 6.{5, 4} ? Sum = 9.{5, 6} ? Sum = 11.{4, 6} ? Sum = 10.{5, 4, 6} ? Sum = 1
14 min read