Find a subarray of size K whose sum is a perfect square
Given an array arr[] and an integer K, the task is to find a subarray of length K having a 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: The 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 the 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 not bool 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 square void 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 Code int 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 approach class GFG{ static class pair { int first, second; } // Function to check if a given number // is a perfect square or not static 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 square static 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 Code public 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 approach from math import sqrt, ceil, floor # Function to check if a given number # is a perfect square or not def 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 print the subarray # whose sum is a perfect square def 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 Code if __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 approach using System; class GFG{ class pair { public int first, second; } // Function to check if a given number // is a perfect square or not static 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 square static 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 Code public 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 |
Javascript
<script> // Javascript program for the above approach // Function to check if a given number // is a perfect square or not function isPerfectSquare(n) { // Find square root of n var 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 square function SubarrayHavingPerfectSquare( arr, k) { var ans = []; var sum = 0, i; // Sum of first K elements for (i = 0; i < k; i++) { sum += arr[i]; } var 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 ( var j = i; j < arr.length; j++) { 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 ( var k = ans[0]; k <= ans[1]; k++) { document.write( arr[k] + " " ); } } // If subarray not found if (found == false ) { document.write( "-1" ); } } // Driver Code // Given array var arr = [20, 34, 51, 10, 99, 87, 23, 45 ]; // Given subarray size K var K = 3; // Function Call SubarrayHavingPerfectSquare(arr, K); </script> |
10 99 87
Time Complexity: O(N*log(sum))
Auxiliary Space:O(1)