Check if the sum of a subarray within a given range is a perfect square or not
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:
- Calculate the sum of the subarray in the given range[].
- Now, use binary search to find the square root of the sum in the range 0 to sum.
- Find the mid element from the start and last value and compare the value of mid2 with the sum.
- If the value of mid2 is equal to the sum, a perfect square is found, then return mid.
- 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.
- 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 rangeint 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 Codeint 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 approachimport java.util.*;class GFG{// Function to calculate the square// root of the sum of a subarray in// a given rangestatic 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 Codepublic 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 rangedef 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 Codeif __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 approachusing System;class GFG{// Function to calculate the square// root of the sum of a subarray in// a given rangestatic 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 Codepublic 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 rangefunction 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 Arraylet arr = [ 2, 19, 33, 48, 90, 100 ];// Given rangelet L = 1, R = 3;// Function Calldocument.write(checkForPerfectSquare(arr, L, R));// This code is contributed by rishavmahato348</script> |
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 experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


