Subarrays whose sum is a perfect square

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
import math
 
# Function to prthe 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

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







 

Time Complexity: O(N2) 
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.




My Personal Notes arrow_drop_up


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.