Open In App

Subarrays whose sum is a perfect square

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, arr[] of size N, the task is to print the start and end indices of all subarrays whose sum is a perfect square.

Examples:

Input: arr[] = {65, 79, 81}
Output: (0, 1) (0, 2) (2, 2)
Explanation: 
Subarray sum whose start and end index is (0, 1) = 65 + 79 = 144 = 122 
Subarray sum whose start and end index is (0, 2} = 65 + 79 + 81 = 225 = 152 
Subarray sum whose start and end index is {2, 2} = 81 = 92

Input: arr[] = {1, 2, 3, 4, 5}
Output: (0, 0) (1, 3) (3, 3) (3, 4) 

Approach: The problem can be solved using the Prefix Sum Array technique. The idea is to find the sum of all subarrays using the Prefix Sum Array. For each subarray, check if the sum of the subarray is a perfect square or not. If found to be true for any subarray, then print the start and end indices of that subarray. Follow the steps below to solve the problem.

  1. Initialize a variable, say currSubSum to store the current subarray sum.
  2. Iterate over the array to generate all possible subarrays of the given array.
  3. Calculate the sum of each subarray and for each subarray sum, check if it is a perfect square or not.
  4. If found to be true for any subarray, then print the start and end indices of the subarray.

Below is the implementation of the above approach:

C++14




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the start and end
// indices of all subarrays whose sum
// is a perfect square
void PrintIndexes(int arr[], int N)
{
 
    for (int i = 0; i < N; i++) {
 
        // Stores the current
        // subarray sum
        int currSubSum = 0;
 
        for (int j = i; j < N; j++) {
 
            // Update current subarray sum
            currSubSum += arr[j];
 
            // Stores the square root
            // of currSubSum
            int sq = sqrt(currSubSum);
 
            // Check if currSubSum is
            // a perfect square or not
            if (sq * sq == currSubSum) {
                cout << "(" << i << ", "
                     << j << ") ";
            }
        }
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { 65, 79, 81 };
    int N = sizeof(arr) / sizeof(arr[0]);
    PrintIndexes(arr, N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
     
// Function to print the start and end
// indices of all subarrays whose sum
// is a perfect square
static void PrintIndexes(int arr[], int N)
{
    for(int i = 0; i < N; i++)
    {
         
        // Stores the current
        // subarray sum
        int currSubSum = 0;
   
        for(int j = i; j < N; j++)
        {
             
            // Update current subarray sum
            currSubSum += arr[j];
   
            // Stores the square root
            // of currSubSum
            int sq = (int)Math.sqrt(currSubSum);
   
            // Check if currSubSum is
            // a perfect square or not
            if (sq * sq == currSubSum)
            {
                System.out.print("(" + i + "," +
                                 j + ")" + " ");
            }
        }
    }
}
 
// Driver code
public static void main (String[] args)
throws java.lang.Exception
{
    int arr[] = { 65, 79, 81 };
     
    PrintIndexes(arr, arr.length);
}
}
 
// This code is contributed by bikram2001jha


Python3




# Python3 program to implement
# the above approach
import math
 
# Function to print the start and end
# indices of all subarrays whose sum
# is a perfect square
def PrintIndexes(arr, N):
  
    for i in range(N):
  
        # Stores the current
        # subarray sum
        currSubSum = 0
  
        for j in range(i, N, 1):
             
            # Update current subarray sum
            currSubSum += arr[j]
  
            # Stores the square root
            # of currSubSum
            sq = int(math.sqrt(currSubSum))
  
            # Check if currSubSum is
            # a perfect square or not
            if (sq * sq == currSubSum):
                print("(", i, ",",
                           j, ")", end = " ")
                            
# Driver Code
arr = [ 65, 79, 81 ]
N = len(arr)
 
PrintIndexes(arr, N)
 
# This code is contributed by sanjoy_62


C#




// C# program to implement
// the above approach
using System;
class GFG{
     
// Function to print the start
// and end indices of all
// subarrays whose sum
// is a perfect square
static void PrintIndexes(int []arr,
                         int N)
{
  for(int i = 0; i < N; i++)
  {
    // Stores the current
    // subarray sum
    int currSubSum = 0;
 
    for(int j = i; j < N; j++)
    {
      // Update current subarray sum
      currSubSum += arr[j];
 
      // Stores the square root
      // of currSubSum
      int sq = (int)Math.Sqrt(currSubSum);
 
      // Check if currSubSum is
      // a perfect square or not
      if (sq * sq == currSubSum)
      {
        Console.Write("(" + i + "," +
                      j + ")" + " ");
      }
    }
  }
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = {65, 79, 81};
  PrintIndexes(arr, arr.Length);
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to print the start and end
// indices of all subarrays whose sum
// is a perfect square
function PrintIndexes(arr, N)
{
    for(let i = 0; i < N; i++)
    {
         
        // Stores the current
        // subarray sum
        let currSubSum = 0;
   
        for(let j = i; j < N; j++)
        {
             
            // Update current subarray sum
            currSubSum += arr[j];
   
            // Stores the square root
            // of currSubSum
            let sq = Math.floor(Math.sqrt(currSubSum));
   
            // Check if currSubSum is
            // a perfect square or not
            if (sq * sq == currSubSum)
            {
                document.write("(" + i + "," +
                                 j + ")" + " ");
            }
        }
    }
}
 
// Driver Code
 
        let arr = [ 65, 79, 81 ];
     
    PrintIndexes(arr, arr.length);
 
</script>


Output: 

(0, 1) (0, 2) (2, 2)

 

Time Complexity: O(N2) 
Auxiliary Space: O(1)



Last Updated : 21 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads