Saturday, December 28, 2024
Google search engine
HomeData Modelling & AISubarrays whose sum is a perfect square

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




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

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 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments