Divide array into two sub-arrays such that their averages are equal - GeeksforGeeks

19 Apr, 2022
Given an integer array, the task is to divide an integer array into two sub-arrays to make their averages equal if possible.Examples :  
Input : arr[] = {1, 5, 7, 2, 0};    
Output : (0  1) and (2  4) 
Subarrays arr[0..1] and arr[2..4] have
same average.

Input : arr[] = {4, 3, 5, 9, 11};
Output : Not possible
Asked in Microsoft  
A Naive Approach is to run two loops and find subarrays whose averages are equal.  
C++
Java
Python 3
C#
PHP
Javascript
// Simple C++ program to find subarrays// whose averages are equal#include<bits/stdc++.h>using namespace std; // Finding two subarrays// with equal average.void findSubarrays(int arr[], int n){    bool found = false;    int lsum = 0;    for (int i = 0; i < n - 1; i++)    {        lsum += arr[i];        int rsum = 0;        for (int j = i + 1; j < n; j++)            rsum += arr[j];         // If averages of arr[0...i] and        // arr[i+1..n-1] are same. To avoid        // floating point problems we compare        // "lsum*(n-i+1)" and "rsum*(i+1)"        // instead of "lsum/(i+1)" and        // "rsum/(n-i+1)"        if (lsum * (n - i - 1) ==               rsum * (i + 1))        {            printf("From (%d %d) to (%d %d)\n",                           0, i, i + 1, n - 1);            found = true;        }    }     // If no subarrays found    if (found == false)        cout << "Subarrays not found"             << endl;} // Driver codeint main(){    int arr[] = {1, 5, 7, 2, 0};    int n = sizeof(arr) / sizeof(arr[0]);    findSubarrays(arr, n);    return 0;}
// Simple Java program to find subarrays// whose averages are equal public class GFG {         // Finding two subarrays    // with equal average.    static void findSubarrays(int[] arr, int n)    {        boolean found = false;        int lsum = 0;                 for (int i = 0; i < n - 1; i++)        {            lsum += arr[i];            int rsum = 0;                         for (int j = i + 1; j < n; j++)                rsum += arr[j];                 // If averages of arr[0...i] and            // arr[i+1..n-1] are same. To avoid            // floating point problems we compare            // "lsum*(n-i+1)" and "rsum*(i+1)"            // instead of "lsum/(i+1)" and            // "rsum/(n-i+1)"            if (lsum * (n - i - 1) ==                                rsum * (i + 1))            {                System.out.println("From (0 " + i                        + ") to (" +(i + 1) + " "                                + (n - 1)+ ")");                                             found = true;            }        }             // If no subarrays found        if (found == false)            System.out.println( "Subarrays not "                                    + "found");    }         // Driver code    static public void main (String[] args)    {        int[] arr = {1, 5, 7, 2, 0};        int n = arr.length;        findSubarrays(arr, n);    }} // This code is contributed by Mukul Singh.
# Simple Python 3 program to find subarrays# whose averages are equal # Finding two subarrays with equal average.def findSubarrays(arr, n):     found = False    lsum = 0    for i in range(n - 1):             lsum += arr[i]        rsum = 0        for j in range(i + 1, n):            rsum += arr[j]         # If averages of arr[0...i] and        # arr[i+1..n-1] are same. To avoid        # floating point problems we compare        # "lsum*(n-i+1)" and "rsum*(i+1)"        # instead of "lsum/(i+1)" and        # "rsum/(n-i+1)"        if (lsum * (n - i - 1) == rsum * (i + 1)):            print("From", "(", 0, i, ")",                  "to", "(", i + 1, n - 1, ")")            found = True     # If no subarrays found    if (found == False):        print("Subarrays not found") # Driver codeif __name__ == "__main__":         arr = [1, 5, 7, 2, 0]    n = len(arr)    findSubarrays(arr, n) # This code is contributed by ita_c
// Simple C# program to find subarrays// whose averages are equalusing System; public class GFG {         // Finding two subarrays    // with equal average.    static void findSubarrays(int []arr, int n)    {        bool found = false;        int lsum = 0;                 for (int i = 0; i < n - 1; i++)        {            lsum += arr[i];            int rsum = 0;                         for (int j = i + 1; j < n; j++)                rsum += arr[j];                 // If averages of arr[0...i] and            // arr[i+1..n-1] are same. To avoid            // floating point problems we compare            // "lsum*(n-i+1)" and "rsum*(i+1)"            // instead of "lsum/(i+1)" and            // "rsum/(n-i+1)"            if (lsum * (n - i - 1) ==                                  rsum * (i + 1))            {                Console.WriteLine("From ( 0 " + i                        + ") to(" + (i + 1) + " "                                + (n - 1) + ")");                                             found = true;            }        }             // If no subarrays found        if (found == false)            Console.WriteLine( "Subarrays not "                                    + "found");    }         // Driver code    static public void Main ()    {        int []arr = {1, 5, 7, 2, 0};        int n = arr.Length;        findSubarrays(arr, n);    }} // This code is contributed by anuj_67.
<?php// Simple PHP program to find subarrays// whose averages are equal // Finding two subarrays// with equal average.function findSubarrays( $arr, $n){    $found = false;    $lsum = 0;    for ( $i = 0; $i < $n - 1; $i++)    {        $lsum += $arr[$i];        $rsum = 0;        for ( $j = $i + 1; $j < $n; $j++)            $rsum += $arr[$j];         // If averages of arr[0...i] and        // arr[i+1..n-1] are same. To avoid        // floating point problems we compare        // "lsum*(n-i+1)" and "rsum*(i+1)"        // instead of "lsum/(i+1)" and "rsum/(n-i+1)"        if ($lsum * ($n - $i - 1) ==                $rsum * ($i + 1))        {        echo "From ( 0 ", $i," )".             " to (", $i + 1," ", $n - 1,")\n";                                                         $found = true;        }    }     // If no subarrays found    if ($found == false)        echo "Subarrays not found" ;} // Driver code$arr = array(1, 5, 7, 2, 0);$n = count($arr);findSubarrays($arr, $n); // This code is contributed by vt_m?>
<script> // Simple Javascript program to find subarrays// whose averages are equal         // Finding two subarrays    // with equal average.    function findSubarrays(arr,n)    {        let found = false;        let lsum = 0;                   for (let i = 0; i < n - 1; i++)        {            lsum += arr[i];            let rsum = 0;                           for (let j = i + 1; j < n; j++)                rsum += arr[j];                   // If averages of arr[0...i] and            // arr[i+1..n-1] are same. To avoid            // floating point problems we compare            // "lsum*(n-i+1)" and "rsum*(i+1)"            // instead of "lsum/(i+1)" and            // "rsum/(n-i+1)"            if (lsum * (n - i - 1) ==                                rsum * (i + 1))            {                document.write("From (0 " + i                        + ") to (" +(i + 1) + " "                                + (n - 1)+ ")");                                               found = true;            }        }               // If no subarrays found        if (found == false)            document.write( "Subarrays not "                                    + "found");    }         // Driver code    let arr=[1, 5, 7, 2, 0];    let n = arr.length;    findSubarrays(arr, n);         // This code is contributed by avanitrachhadiya2155     </script>
Output : 
From (0  1) to (2  4)
Time complexity : O(n2) Auxiliary Space : O(1)An Efficient solution is to find sum of array elements. Initialize leftsum as zero. Run a loop and find leftsum by adding elements of array. For rightsum, we subtract leftsum from total sum then we find rightsum and find average of leftsum and rightsum as according to their index. 
1) Compute sum of all array elements. Let this 
   sum be "sum"
2) Initialize leftsum = 0.
3) Run a loop for i=0 to n-1.
    a) leftsum  = leftsum + arr[i]
    b) rightsum = sum - leftsum
    c) If average of left and right are same, 
       print current index as output.
Below is the implementation for above approach: 
C++
Java
Python3
C#
Javascript
// Efficient C++ program for// dividing array to make// average equal#include<bits/stdc++.h>using namespace std; void findSubarrays(int arr[], int n){    // Find array sum    int sum = 0;    for (int i = 0; i < n; i++)        sum += arr[i];     bool found = false;    int lsum = 0;    for (int i = 0; i < n - 1; i++)    {        lsum += arr[i];        int rsum = sum - lsum;         // If averages of arr[0...i]        // and arr[i+1..n-1] are same.        // To avoid floating point problems        // we compare "lsum*(n-i+1)"        // and "rsum*(i+1)" instead of        // "lsum/(i+1)" and "rsum/(n-i+1)"        if (lsum * (n - i - 1) == rsum * (i + 1))        {            printf("From (%d %d) to (%d %d)\n",                               0, i, i+1, n-1);            found = true;        }    }     // If no subarrays found    if (found == false)        cout << "Subarrays not found"             << endl;} // Driver codeint main(){    int arr[] = {1, 5, 7, 2, 0};    int n = sizeof(arr) / sizeof(arr[0]);    findSubarrays(arr, n);    return 0;}
// Efficient Java program for// dividing array to make// average equalimport java.util.*;     class GFG{static void findSubarrays(int arr[], int n){    // Find array sum    int sum = 0;    for (int i = 0; i < n; i++)        sum += arr[i];     boolean found = false;    int lsum = 0;    for (int i = 0; i < n - 1; i++)    {        lsum += arr[i];        int rsum = sum - lsum;         // If averages of arr[0...i]        // and arr[i+1..n-1] are same.        // To avoid floating point problems        // we compare "lsum*(n-i+1)"        // and "rsum*(i+1)" instead of        // "lsum/(i+1)" and "rsum/(n-i+1)"        if (lsum * (n - i - 1) == rsum * (i + 1))        {            System.out.printf("From (%d %d) to (%d %d)\n",                                      0, i, i + 1, n - 1);            found = true;        }    }     // If no subarrays found    if (found == false)        System.out.println("Subarrays not found");} // Driver codestatic public void main ( String []arg){    int arr[] = {1, 5, 7, 2, 0};    int n = arr.length;    findSubarrays(arr, n);}} // This code is contributed by Princi Singh
# Efficient Python program for# dividing array to make# average equal def findSubarrays(arr, n):     # Find array sum    sum = 0;    for i in range(n):        sum += arr[i];     found = False;    lsum = 0;    for i in range(n - 1):        lsum += arr[i];        rsum = sum - lsum;         # If averages of arr[0...i]        # and arr[i + 1..n - 1] are same.        # To avoid floating point problems        # we compare "lsum*(n - i + 1)"        # and "rsum*(i + 1)" instead of        # "lsum / (i + 1)" and "rsum/(n - i + 1)"        if (lsum * (n - i - 1) == rsum * (i + 1)):            print("From (%d %d) to (%d %d)\n"%                   (0, i, i + 1, n - 1));            found = True;             # If no subarrays found    if (found == False):        print("Subarrays not found"); # Driver codeif __name__ == '__main__':    arr = [ 1, 5, 7, 2, 0 ];    n = len(arr);    findSubarrays(arr, n); # This code is contributed by Rajput-Ji
// Efficient C# program for// dividing array to make// average equalusing System;     class GFG{static void findSubarrays(int []arr, int n){    // Find array sum    int sum = 0;    for (int i = 0; i < n; i++)        sum += arr[i];     bool found = false;    int lsum = 0;    for (int i = 0; i < n - 1; i++)    {        lsum += arr[i];        int rsum = sum - lsum;         // If averages of arr[0...i]        // and arr[i+1..n-1] are same.        // To avoid floating point problems        // we compare "lsum*(n-i+1)"        // and "rsum*(i+1)" instead of        // "lsum/(i+1)" and "rsum/(n-i+1)"        if (lsum * (n - i - 1) == rsum * (i + 1))        {            Console.Write("From ({0} {1}) to ({2} {3})\n",                                      0, i, i + 1, n - 1);            found = true;        }    }     // If no subarrays found    if (found == false)        Console.WriteLine("Subarrays not found");} // Driver codestatic public void Main ( String []arg){    int []arr = {1, 5, 7, 2, 0};    int n = arr.Length;    findSubarrays(arr, n);}}     // This code is contributed by Rajput-Ji
<script> // Efficient Javascript program for// dividing array to make// average equal         function findSubarrays(arr,n)    {    // Find array sum    let sum = 0;    for (let i = 0; i < n; i++)        sum += arr[i];     let found = false;    let lsum = 0;    for (let i = 0; i < n - 1; i++)    {        lsum += arr[i];        let rsum = sum - lsum;         // If averages of arr[0...i]        // and arr[i+1..n-1] are same.        // To avoid floating point problems        // we compare "lsum*(n-i+1)"        // and "rsum*(i+1)" instead of        // "lsum/(i+1)" and "rsum/(n-i+1)"        if (lsum * (n - i - 1) == rsum * (i + 1))        {            document.write(       "From (0 "+i+") to ("+(i+1)+" "+(n-1)+")\n"      );                                                   found = true;        }    }     // If no subarrays found    if (found == false)        document.write("Subarrays not found");    }    // Driver code    let arr=[1, 5, 7, 2, 0];    let n = arr.length;    findSubarrays(arr, n);         // This code is contributed by rag2127 </script>
Output : 
From (0  1) to (2  4)
Time complexity : O(n) Auxiliary Space : O(1)This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
ukasp
Code_Mech
princi singh
Rajput-Ji
Akanksha_Rai
avanitrachhadiya2155
rag2127
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times