Given an array arr[] and an integer K, the task is to find a subarray of length K having sum which is a perfect square. If no such subarray exists, then print -1. Otherwise, print the subarray.
Note: There can be more than one possible subarray. Print any one of them.
Examples:
Input: arr[] = {20, 34, 51, 10, 99, 87, 23, 45}, K = 3
Output: {10, 99, 87}
Explanation: Sum of the elements of the subarray {10, 99, 87} is 196 which is a perfect square (162 = 196).Input: arr[] = {20, 34, 51, 10, 99, 87, 23, 45}, K = 4
Output: -1
Explanation: None of the subarrays of size K has a sum which is a perfect square.
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays of size K and check whether the sum of any subarray generated is a perfect square or not. If found to be true, print that subarray. If no subarray satisfies the condition, print “-1”.
Time Complexity: O(N*K)
Auxiliary Space: O(K)
Efficient Approach: An efficient approach is to use a sliding window technique to find the sum of a contiguous subarray of size K and then check if the sum is a perfect square or not using Binary Search. Below are the steps to solve this problem:
- Compute the sum of first K array elements and store it in a variable, say curr_sum.
- Then iterate over the remaining array elements one by one, and update curr_sum by adding ith element and removing (i – K)th element from the array.
- For every value of curr_sum obtained, check if it is a perfect square number or not.
- If found to be true for any value of curr_sum, then print the corresponding subarray.
- Otherwise, print -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function to check if a given number// is a perfect square or notbool isPerfectSquare(int n){ // Find square root of n double sr = sqrt(n); // Check if the square root // is an integer or not return ((sr - floor(sr)) == 0);}// Function to print the subarray// whose sum is a perfect squarevoid SubarrayHavingPerfectSquare( vector<int> arr, int k){ pair<int, int> ans; int sum = 0, i; // Sum of first K elements for (i = 0; i < k; i++) { sum += arr[i]; } bool found = false; // If the first k elements have // a sum as perfect square if (isPerfectSquare(sum)) { ans.first = 0; ans.second = i - 1; } else { // Iterate through the array for (int j = i; j < arr.size(); j++) { sum = sum + arr[j] - arr[j - k]; // If sum is perfect square if (isPerfectSquare(sum)) { found = true; ans.first = j - k + 1; ans.second = j; } } for (int k = ans.first; k <= ans.second; k++) { cout << arr[k] << " "; } } // If subarray not found if (found == false) { cout << "-1"; }}// Driver Codeint main(){ // Given array vector<int> arr; arr = { 20, 34, 51, 10, 99, 87, 23, 45 }; // Given subarray size K int K = 3; // Function Call SubarrayHavingPerfectSquare(arr, K); return 0;} |
Java
// Java program for // the above approachclass GFG{ static class pair{ int first, second; }// Function to check if a given number// is a perfect square or notstatic boolean isPerfectSquare(int n){ // Find square root of n double sr = Math.sqrt(n); // Check if the square root // is an integer or not return ((sr - Math.floor(sr)) == 0);}// Function to print the subarray// whose sum is a perfect squarestatic void SubarrayHavingPerfectSquare(int[] arr, int k){ pair ans = new pair(); int sum = 0, i; // Sum of first K elements for (i = 0; i < k; i++) { sum += arr[i]; } boolean found = false; // If the first k elements have // a sum as perfect square if (isPerfectSquare(sum)) { ans.first = 0; ans.second = i - 1; } else { // Iterate through the array for (int j = i; j < arr.length; j++) { sum = sum + arr[j] - arr[j - k]; // If sum is perfect square if (isPerfectSquare(sum)) { found = true; ans.first = j - k + 1; ans.second = j; } } for (int k1 = ans.first; k1 <= ans.second; k1++) { System.out.print(arr[k1] + " "); } } // If subarray not found if (found == false) { System.out.print("-1"); }}// Driver Codepublic static void main(String[] args){ // Given array int []arr = {20, 34, 51, 10, 99, 87, 23, 45}; // Given subarray size K int K = 3; // Function Call SubarrayHavingPerfectSquare(arr, K);}}// This code is contributed by Rajput-Ji |
Python3
# Python3 program for the above approachfrom math import sqrt, ceil, floor# Function to check if a given number# is a perfect square or notdef isPerfectSquare(n): # Find square root of n sr = sqrt(n) # Check if the square root # is an integer or not return ((sr - floor(sr)) == 0)# Function to prthe subarray# whose sum is a perfect squaredef SubarrayHavingPerfectSquare(arr, k): ans = [ 0, 0 ] sum = 0 # Sum of first K elements i = 0 while i < k: sum += arr[i] i += 1 found = False # If the first k elements have # a sum as perfect square if (isPerfectSquare(sum)): ans[0] = 0 ans[1] = i - 1 else: # Iterate through the array for j in range(i, len(arr)): sum = sum + arr[j] - arr[j - k] # If sum is perfect square if (isPerfectSquare(sum)): found = True ans[0] = j - k + 1 ans[1] = j for k in range(ans[0], ans[1] + 1): print(arr[k], end = " ") # If subarray not found if (found == False): print("-1")# Driver Codeif __name__ == '__main__': # Given array arr = [ 20, 34, 51, 10, 99, 87, 23, 45 ] # Given subarray size K K = 3 # Function call SubarrayHavingPerfectSquare(arr, K)# This code is contributed by mohit kumar 29 |
C#
// C# program for // the above approachusing System;class GFG{ class pair{ public int first, second; } // Function to check if a given number// is a perfect square or notstatic bool isPerfectSquare(int n){ // Find square root of n double sr = Math.Sqrt(n); // Check if the square root // is an integer or not return ((sr - Math.Floor(sr)) == 0);}// Function to print the subarray// whose sum is a perfect squarestatic void SubarrayHavingPerfectSquare(int[] arr, int k){ pair ans = new pair(); int sum = 0, i; // Sum of first K elements for (i = 0; i < k; i++) { sum += arr[i]; } bool found = false; // If the first k elements have // a sum as perfect square if (isPerfectSquare(sum)) { ans.first = 0; ans.second = i - 1; } else { // Iterate through the array for (int j = i; j < arr.Length; j++) { sum = sum + arr[j] - arr[j - k]; // If sum is perfect square if (isPerfectSquare(sum)) { found = true; ans.first = j - k + 1; ans.second = j; } } for (int k1 = ans.first; k1 <= ans.second; k1++) { Console.Write(arr[k1] + " "); } } // If subarray not found if (found == false) { Console.Write("-1"); }}// Driver Codepublic static void Main(String[] args){ // Given array int []arr = {20, 34, 51, 10, 99, 87, 23, 45}; // Given subarray size K int K = 3; // Function Call SubarrayHavingPerfectSquare(arr, K);}}// This code is contributed by Rajput-Ji |
10 99 87
Time Complexity: O(N*log(sum))
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.
Recommended Posts:
- Find smallest perfect square number A such that N + A is also a perfect square number
- Check if a number is a perfect square having all its digits as a perfect square
- Smallest N digit number whose sum of square of digits is a Perfect Square
- Construct an Array of size N whose sum of cube of all elements is a perfect square
- Count numbers upto N which are both perfect square and perfect cube
- Check if the sum of a subarray within a given range is a perfect square or not
- Count of pairs in an array whose sum is a perfect square
- Subarrays whose sum is a perfect square
- Count of subarrays whose sum is a perfect square
- First subarray having sum at least half the maximum sum of any subarray of size K
- Check if a number is perfect square without finding square root
- Find a subarray whose sum is divisible by size of the array
- Count of pairs in an array whose product is a perfect square
- Length of largest subarray whose all elements are Perfect Number
- Maximum number of Perfect Numbers present in a subarray of size K
- Construct a square Matrix whose parity of diagonal sum is same as size of matrix
- Maximum size of square such that all submatrices of that size have sum less than K
- Smallest subarray whose sum is multiple of array size
- Maximum subarray size, such that all subarrays of that size have sum less than k
- Count squares of size K inscribed in a square of size N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

