Skip to content
Related Articles

Related Articles

Improve Article
Check if the sum of a subarray within a given range is a perfect square or not
  • Last Updated : 09 Apr, 2021

Given an array arr[] of size N and an array range[], the task is to check if the sum of the subarray {range[0], .. , range[1]} is a perfect square or not. If the sum is a perfect square, then print the square root of the sum. Otherwise, print -1.

Example :

Input: arr[] = {2, 19, 33, 48, 90, 100}, range = [1, 3] 
Output: 10 
Explanation: 
The sum of element from position 1 to position 3 is 19 + 33 + 48 = 100, which is a perfect square of 10.

Input: arr[] = {13, 15, 30, 55, 87}, range = [0, 1] 
Output: -1

Naive Approach: The simplest approach is to iterate over the subarray and check if the sum of the subarray is a perfect square or not.



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

Efficient Approach: To optimize the above approach, the idea is to use Binary Search to calculate the square root of the sum of the subarray. Follow the steps below:

  1. Calculate the sum of the subarray in the given range[].
  2. Now, use binary search to find the square root of the sum in the range 0 to sum.
  3. Find the mid element from the start and last value and compare the value of mid2 with the sum.
  4. If the value of mid2 is equal to the sum, a perfect square is found, then return mid.
  5. If the value of mid2 is greater than the sum, then the answer can lie only on the right side of the range after the mid element. So recur for right and reduce the search space to 0 to mid – 1.
  6. If the value of mid2 is less than the sum, reduce the search space to mid + 1 to sum.

Below is the implementation of the above approach.

C++




// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
int checkForPerfectSquare(vector<int> arr,
                          int i, int j)
{
    int mid, sum = 0;
 
    // Calculate the sum of array
    // elements within a given range
    for (int m = i; m <= j; m++) {
        sum += arr[m];
    }
 
    // Finding the square root
    int low = 0, high = sum / 2;
    while (low <= high) {
        mid = low + (high - low) / 2;
 
        // If a perfect square is found
        if (mid * mid == sum) {
            return mid;
        }
 
        // Reduce the search space if
        // the value is greater than sum
        else if (mid * mid > sum) {
            high = mid - 1;
        }
 
        // Reduce the search space if
        // the value if smaller than sum
        else {
            low = mid + 1;
        }
    }
    return -1;
}
 
// Driver Code
int main()
{
    // Given Array
    vector<int> arr;
    arr = { 2, 19, 33, 48, 90, 100 };
 
    // Given range
    int L = 1, R = 3;
 
    // Function Call
    cout << checkForPerfectSquare(arr, L, R);
    return 0;
}

Java




// Java implementation of
// the above approach
import java.util.*;
class GFG{
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
static int checkForPerfectSquare(int []arr,
                                 int i, int j)
{
  int mid, sum = 0;
 
  // Calculate the sum of array
  // elements within a given range
  for (int m = i; m <= j; m++)
  {
    sum += arr[m];
  }
 
  // Finding the square root
  int low = 0, high = sum / 2;
  while (low <= high)
  {
    mid = low + (high - low) / 2;
 
    // If a perfect square
    // is found
    if (mid * mid == sum)
    {
      return mid;
    }
 
    // Reduce the search space
    // if the value is greater
    // than sum
    else if (mid * mid > sum)
    {
      high = mid - 1;
    }
 
    // Reduce the search space
    // if the value if smaller
    // than sum
    else
    {
      low = mid + 1;
    }
  }
  return -1;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given Array
  int []arr = {2, 19, 33,
               48, 90, 100};
 
  // Given range
  int L = 1, R = 3;
 
  // Function Call
  System.out.print(
         checkForPerfectSquare(arr, L, R));
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 implementation of
# the above approach
 
# Function to calculate the square
# root of the sum of a subarray in
# a given range
def checkForPerfectSquare(arr, i, j):
 
    mid, sum = 0, 0
 
    # Calculate the sum of array
    # elements within a given range
    for m in range(i, j + 1):
        sum += arr[m]
 
    # Finding the square root
    low = 0
    high = sum // 2
     
    while (low <= high):
        mid = low + (high - low) // 2
 
        # If a perfect square is found
        if (mid * mid == sum):
            return mid
 
        # Reduce the search space if
        # the value is greater than sum
        elif (mid * mid > sum):
            high = mid - 1
 
        # Reduce the search space if
        # the value if smaller than sum
        else:
            low = mid + 1
 
    return -1
 
# Driver Code
if __name__ == '__main__':
 
    # Given Array
    arr = [ 2, 19, 33, 48, 90, 100 ]
 
    # Given range
    L = 1
    R = 3
 
    # Function call
    print(checkForPerfectSquare(arr, L, R))
 
# This code is contributed by mohit kumar 29

C#




// C# implementation of
// the above approach
using System;
class GFG{
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
static int checkForPerfectSquare(int []arr,
                                 int i, int j)
{
  int mid, sum = 0;
 
  // Calculate the sum of array
  // elements within a given range
  for (int m = i; m <= j; m++)
  {
    sum += arr[m];
  }
 
  // Finding the square root
  int low = 0, high = sum / 2;
  while (low <= high)
  {
    mid = low + (high - low) / 2;
 
    // If a perfect square
    // is found
    if (mid * mid == sum)
    {
      return mid;
    }
 
    // Reduce the search space
    // if the value is greater
    // than sum
    else if (mid * mid > sum)
    {
      high = mid - 1;
    }
 
    // Reduce the search space
    // if the value if smaller
    // than sum
    else
    {
      low = mid + 1;
    }
  }
  return -1;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given Array
  int []arr = {2, 19, 33,
               48, 90, 100};
 
  // Given range
  int L = 1, R = 3;
 
  // Function Call
  Console.Write(checkForPerfectSquare(arr,
                                      L, R));}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// Javascript implementation of
// the above approach
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
function checkForPerfectSquare(arr, i, j)
{
    let mid, sum = 0;
 
    // Calculate the sum of array
    // elements within a given range
    for(let m = i; m <= j; m++)
    {
        sum += arr[m];
    }
 
    // Finding the square root
    let low = 0, high = parseInt(sum / 2);
     
    while (low <= high)
    {
        mid = low + parseInt((high - low) / 2);
 
        // If a perfect square is found
        if (mid * mid == sum)
        {
            return mid;
        }
 
        // Reduce the search space if
        // the value is greater than sum
        else if (mid * mid > sum)
        {
            high = mid - 1;
        }
 
        // Reduce the search space if
        // the value if smaller than sum
        else
        {
            low = mid + 1;
        }
    }
    return -1;
}
 
// Driver Code
 
// Given Array
let arr = [ 2, 19, 33, 48, 90, 100 ];
 
// Given range
let L = 1, R = 3;
 
// Function Call
document.write(checkForPerfectSquare(arr, L, R));
 
// This code is contributed by rishavmahato348
 
</script>
Output: 
10

Time Complexity: O(max(log(sum), N)) 
Auxiliary Space: O(1) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :