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++
#include <bits/stdc++.h>
using namespace std;
bool isPerfectSquare( int n)
{
double sr = sqrt (n);
return ((sr - floor (sr)) == 0);
}
void SubarrayHavingPerfectSquare(
vector< int > arr, int k)
{
pair< int , int > ans;
int sum = 0, i;
for (i = 0; i < k; i++) {
sum += arr[i];
}
bool found = false ;
if (isPerfectSquare(sum)) {
ans.first = 0;
ans.second = i - 1;
}
else {
for ( int j = i;
j < arr.size(); j++) {
sum = sum + arr[j] - arr[j - k];
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 (found == false ) {
cout << "-1" ;
}
}
int main()
{
vector< int > arr;
arr = { 20, 34, 51, 10,
99, 87, 23, 45 };
int K = 3;
SubarrayHavingPerfectSquare(arr, K);
return 0;
}
|
Java
import java.io.*;
public class GFG{
static class pair
{
int first, second;
}
static boolean isPerfectSquare( int n)
{
double sr = Math.sqrt(n);
return ((sr - Math.floor(sr)) == 0 );
}
static void SubarrayHavingPerfectSquare( int [] arr,
int k)
{
pair ans = new pair();
int sum = 0 , i;
for (i = 0 ; i < k; i++)
{
sum += arr[i];
}
boolean found = false ;
if (isPerfectSquare(sum))
{
ans.first = 0 ;
ans.second = i - 1 ;
}
else
{
for ( int j = i; j < arr.length; j++)
{
sum = sum + arr[j] - arr[j - k];
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 (found == false )
{
System.out.print( "-1" );
}
}
public static void main(String[] args)
{
int []arr = { 20 , 34 , 51 , 10 ,
99 , 87 , 23 , 45 };
int K = 3 ;
SubarrayHavingPerfectSquare(arr, K);
}
}
|
Python3
from math import sqrt, ceil, floor
def isPerfectSquare(n):
sr = sqrt(n)
return ((sr - floor(sr)) = = 0 )
def SubarrayHavingPerfectSquare(arr, k):
ans = [ 0 , 0 ]
sum = 0
i = 0
while i < k:
sum + = arr[i]
i + = 1
found = False
if (isPerfectSquare( sum )):
ans[ 0 ] = 0
ans[ 1 ] = i - 1
else :
for j in range (i, len (arr)):
sum = sum + arr[j] - arr[j - k]
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 (found = = False ):
print ( "-1" )
if __name__ = = '__main__' :
arr = [ 20 , 34 , 51 , 10 ,
99 , 87 , 23 , 45 ]
K = 3
SubarrayHavingPerfectSquare(arr, K)
|
C#
using System;
class GFG{
class pair
{
public int first, second;
}
static bool isPerfectSquare( int n)
{
double sr = Math.Sqrt(n);
return ((sr - Math.Floor(sr)) == 0);
}
static void SubarrayHavingPerfectSquare( int [] arr,
int k)
{
pair ans = new pair();
int sum = 0, i;
for (i = 0; i < k; i++)
{
sum += arr[i];
}
bool found = false ;
if (isPerfectSquare(sum))
{
ans.first = 0;
ans.second = i - 1;
}
else
{
for ( int j = i; j < arr.Length; j++)
{
sum = sum + arr[j] - arr[j - k];
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 (found == false )
{
Console.Write( "-1" );
}
}
public static void Main(String[] args)
{
int []arr = {20, 34, 51, 10,
99, 87, 23, 45};
int K = 3;
SubarrayHavingPerfectSquare(arr, K);
}
}
|
Javascript
<script>
function isPerfectSquare(n)
{
var sr = Math.sqrt(n);
return ((sr - Math.floor(sr)) == 0);
}
function SubarrayHavingPerfectSquare( arr, k)
{
var ans = [];
var sum = 0, i;
for (i = 0; i < k; i++) {
sum += arr[i];
}
var found = false ;
if (isPerfectSquare(sum)) {
ans[0] = 0;
ans[1] = i - 1;
}
else {
for ( var j = i;
j < arr.length; j++) {
sum = sum + arr[j] - arr[j - k];
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 (found == false ) {
document.write( "-1" );
}
}
var arr = [20, 34, 51, 10,
99, 87, 23, 45 ];
var K = 3;
SubarrayHavingPerfectSquare(arr, K);
</script>
|
Time Complexity: O(N*log(sum))
Auxiliary Space:O(1)
Approach 2: Dynamic Programming:
To solve this problem using dynamic programming, we can create a 2D array where dp[i][j] represents the sum of the subarray from index i to index j. We can calculate the values of dp[i][j] using the following recurrence relation:
- dp[i][j] = dp[i][j-1] + arr[j]
- Then, we can iterate over all subarrays of size K and check if the sum of the subarray is a perfect square. If we find such a subarray, we can print it and return.
Here’s the codes:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPerfectSquare( int n)
{
int sr = sqrt (n);
return ((sr * sr) == n);
}
void SubarrayHavingPerfectSquare(
vector< int >& arr, int K)
{
int n = arr.size();
int dp[n][n];
memset (dp, 0, sizeof (dp));
for ( int i = 0; i < n; i++) {
dp[i][i] = arr[i];
for ( int j = i + 1; j < n; j++) {
dp[i][j] = dp[i][j - 1] + arr[j];
}
}
bool found = false ;
for ( int i = 0; i <= n - K; i++) {
int sum = dp[i][i + K - 1];
if (isPerfectSquare(sum)) {
found = true ;
for ( int j = i; j < i + K; j++) {
cout << arr[j] << " " ;
}
break ;
}
}
if (found == false ) {
cout << "-1" ;
}
}
int main()
{
vector< int > arr = { 20, 34, 51, 10, 99, 87, 23, 45 };
int K = 3;
SubarrayHavingPerfectSquare(arr, K);
return 0;
}
|
Java
import java.util.*;
public class SubarrayHavingPerfectSquare {
static boolean isPerfectSquare( int n) {
int sr = ( int )Math.sqrt(n);
return (sr * sr == n);
}
static void subarrayHavingPerfectSquare(List<Integer> arr, int K) {
int n = arr.size();
int [][] dp = new int [n][n];
for ( int i = 0 ; i < n; i++) {
dp[i][i] = arr.get(i);
for ( int j = i + 1 ; j < n; j++) {
dp[i][j] = dp[i][j - 1 ] + arr.get(j);
}
}
boolean found = false ;
for ( int i = 0 ; i <= n - K; i++) {
int sum = dp[i][i + K - 1 ];
if (isPerfectSquare(sum)) {
found = true ;
for ( int j = i; j < i + K; j++) {
System.out.print(arr.get(j) + " " );
}
break ;
}
}
if (found == false ) {
System.out.print( "-1" );
}
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList( 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 );
int K = 3 ;
subarrayHavingPerfectSquare(arr, K);
}
}
|
Python3
import math
def isPerfectSquare(n):
sr = int (math.sqrt(n))
return sr * sr = = n
def SubarrayHavingPerfectSquare(arr, K):
n = len (arr)
dp = [[ 0 ] * n for _ in range (n)]
for i in range (n):
dp[i][i] = arr[i]
for j in range (i + 1 , n):
dp[i][j] = dp[i][j - 1 ] + arr[j]
found = False
for i in range (n - K + 1 ):
sum = dp[i][i + K - 1 ]
if isPerfectSquare( sum ):
found = True
for j in range (i, i + K):
print (arr[j], end = " " )
break
if not found:
print ( "-1" )
if __name__ = = "__main__" :
arr = [ 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 ]
K = 3
SubarrayHavingPerfectSquare(arr, K)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static bool IsPerfectSquare( int n)
{
int sr = ( int )Math.Sqrt(n);
return (sr * sr == n);
}
static void SubarrayHavingPerfectSquare(List< int > arr, int K)
{
int n = arr.Count;
int [,] dp = new int [n, n];
for ( int i = 0; i < n; i++)
{
dp[i, i] = arr[i];
for ( int j = i + 1; j < n; j++)
{
dp[i, j] = dp[i, j - 1] + arr[j];
}
}
bool found = false ;
for ( int i = 0; i <= n - K; i++)
{
int sum = dp[i, i + K - 1];
if (IsPerfectSquare(sum))
{
found = true ;
for ( int j = i; j < i + K; j++)
{
Console.Write(arr[j] + " " );
}
break ;
}
}
if (!found)
{
Console.Write( "-1" );
}
}
public static void Main( string [] args)
{
List< int > arr = new List< int > { 20, 34, 51, 10, 99, 87, 23, 45 };
int K = 3;
SubarrayHavingPerfectSquare(arr, K);
}
}
|
Javascript
function isPerfectSquare(n) {
let sr = Math.floor(Math.sqrt(n));
return sr * sr === n;
}
function subarrayHavingPerfectSquare(arr, K) {
let n = arr.length;
let dp = new Array(n).fill(0).map(() => new Array(n).fill(0));
for (let i = 0; i < n; i++) {
dp[i][i] = arr[i];
for (let j = i + 1; j < n; j++) {
dp[i][j] = dp[i][j - 1] + arr[j];
}
}
let found = false ;
for (let i = 0; i <= n - K; i++) {
let sum = dp[i][i + K - 1];
if (isPerfectSquare(sum)) {
found = true ;
for (let j = i; j < i + K; j++) {
console.log(arr[j]);
}
break ;
}
}
if (!found) {
console.log( "-1" );
}
}
let arr = [20, 34, 51, 10, 99, 87, 23, 45];
let K = 3;
subarrayHavingPerfectSquare(arr, K);
|
Output:
10 99 87
Time Complexity: O(n * sqrt(n)), where n is the size of the input array.
Auxiliary Space :O(1)