Given a unsorted integer array arr[] and an integer K. The task is to count the number of subarray with exactly K Perfect Square Numbers.
Examples:
Input: arr[] = {2, 4, 9, 3}, K = 2
Output: 4
Explanation:
Since total number of perfect square number in the array are 2.
So the 4 subarrays with 2 perfect square number are:
1.{2, 4, 9}
2.{2, 4, 9, 3}
3.{4, 9}
4.{4, 9, 3}
Input: arr[] = {4, 2, 5}, K = 3
Output: 0
Simple Approach:
Generate all the subarrays and count the number of perfect numbers in the given subarray if the count is equal to K increment the count for ans variable.
Time Complexity: O(N2)
Efficient Approach:
- Traverse the given array arr[] and check whether the element is Perfect Square or not.
- If the current element is Perfect Square then change the value of array at that index to 1, Else change the value at that index to 0.
- Now the given array is converted into Binary Array.
- Now, Find the count of subarray with sum equals to K in the above Binary Array using the approach discussed in this article.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPerfectSquare( long double x)
{
long double sr = sqrt (x);
return ((sr - floor (sr)) == 0);
}
int findSubarraySum( int arr[], int n, int K)
{
unordered_map< int , int > prevSum;
int res = 0;
int currsum = 0;
for ( int i = 0; i < n; i++) {
currsum += arr[i];
if (currsum == K) {
res++;
}
if (prevSum.find(currsum - K)
!= prevSum.end())
res += (prevSum[currsum - K]);
prevSum[currsum]++;
}
return res;
}
void countSubarray( int arr[], int n, int K)
{
for ( int i = 0; i < n; i++) {
if (isPerfectSquare(arr[i])) {
arr[i] = 1;
}
else {
arr[i] = 0;
}
}
cout << findSubarraySum(arr, n, K);
}
int main()
{
int arr[] = { 2, 4, 9, 2 };
int K = 2;
int N = sizeof (arr) / sizeof (arr[0]);
countSubarray(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean isPerfectSquare( double x)
{
double sr = Math.sqrt(x);
return ((sr - Math.floor(sr)) == 0 );
}
static int findSubarraySum( int arr[],
int n, int K)
{
Map<Integer, Integer> prevSum = new HashMap<>();
int res = 0 ;
int currsum = 0 ;
for ( int i = 0 ; i < n; i++)
{
currsum += arr[i];
if (currsum == K)
{
res++;
}
if (prevSum.containsKey(currsum - K))
res += (prevSum.get(currsum - K));
prevSum.put(currsum,
prevSum.getOrDefault(currsum, 0 ) + 1 );
}
return res;
}
static void countSubarray( int arr[], int n, int K)
{
for ( int i = 0 ; i < n; i++)
{
if (isPerfectSquare(arr[i]))
{
arr[i] = 1 ;
}
else
{
arr[i] = 0 ;
}
}
System.out.println(findSubarraySum(arr, n, K));
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 9 , 2 };
int K = 2 ;
int N = arr.length;
countSubarray(arr, N, K);
}
}
|
Python3
from collections import defaultdict
import math
def isPerfectSquare(x):
sr = math.sqrt(x)
return ((sr - math.floor(sr)) = = 0 )
def findSubarraySum(arr, n, K):
prevSum = defaultdict( int )
res = 0
currsum = 0
for i in range (n):
currsum + = arr[i]
if (currsum = = K):
res + = 1
if ((currsum - K) in prevSum):
res + = (prevSum[currsum - K])
prevSum[currsum] + = 1
return res
def countSubarray(arr, n, K):
for i in range (n):
if (isPerfectSquare(arr[i])):
arr[i] = 1
else :
arr[i] = 0
print (findSubarraySum(arr, n, K))
if __name__ = = "__main__" :
arr = [ 2 , 4 , 9 , 2 ]
K = 2
N = len (arr)
countSubarray(arr, N, K)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static bool isPerfectSquare( double x)
{
double sr = Math.Sqrt(x);
return ((sr - Math.Floor(sr)) == 0);
}
static int findSubarraySum( int []arr,
int n, int K)
{
Dictionary< int ,
int > prevSum = new Dictionary< int ,
int >();
int res = 0;
int currsum = 0;
for ( int i = 0; i < n; i++)
{
currsum += arr[i];
if (currsum == K)
{
res++;
}
if (prevSum.ContainsKey(currsum - K))
res += (prevSum[currsum - K]);
if (prevSum.ContainsKey(currsum))
{
prevSum[currsum]++;
}
else
{
prevSum[currsum] = 1;
}
}
return res;
}
static void countSubarray( int []arr, int n,
int K)
{
for ( int i = 0; i < n; i++)
{
if (isPerfectSquare(arr[i]))
{
arr[i] = 1;
}
else
{
arr[i] = 0;
}
}
Console.Write(findSubarraySum(arr, n, K));
}
public static void Main( string [] args)
{
int []arr = { 2, 4, 9, 2 };
int K = 2;
int N = arr.Length;
countSubarray(arr, N, K);
}
}
|
Javascript
<script>
function isPerfectSquare(x)
{
let sr = Math.sqrt(x);
return ((sr - Math.floor(sr)) == 0);
}
function findSubarraySum(arr, n, k)
{
let prevSum = new Map();
let res = 0;
let currsum = 0;
for (let i = 0; i < n; i++)
{
currsum += arr[i];
if (currsum == K)
{
res++;
}
if (prevSum.has(currsum - K))
res += (prevSum.get(currsum - K));
prevSum.set(currsum,
prevSum.get(currsum)== null ?1:prevSum.get(currsum) + 1);
}
return res;
}
function countSubarray(arr, n, k)
{
for (let i = 0; i < n; i++)
{
if (isPerfectSquare(arr[i]))
{
arr[i] = 1;
}
else
{
arr[i] = 0;
}
}
document.write(findSubarraySum(arr, n, K));
}
let arr=[2, 4, 9, 2];
let K = 2;
let N = arr.length;
countSubarray(arr, N, K);
</script>
|
Time Complexity: O(N)
Space Complexity: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!