Open In App

Smallest index that splits an array into two subarrays with equal product

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array(1-based indexing) arr[] consisting of N non zero integers, the task is to find the leftmost index i such that the product of all the elements of the subarrays arr[1, i] and arr[i + 1, N] is the same.

Examples:

Input: arr[] = {1, 2, 3, 3, 2, 1}
Output: 3
Explanation: Index 3 generates subarray {arr[1], arr[3]} with product 6 (= 1 * 2 * 3) and {arr[4], arr[6]} with product 6 ( = 3 * 2 * 1).

Input: arr = {3, 2, 6}
Output: 2

Brute Force Approach:

To solve this problem is to iterate through the array and keep track of the product of the elements from the beginning of the array to the current index and from the current index to the end of the array. For each index i, if the product of the two subarrays is equal, return i. If no such index is found, return -1.

Implementation of the above approach:

C++




#include <iostream>
using namespace std;
 
// Function to find the smallest index that splits the array
// into two subarrays with equal product
void prodEquilibrium(int arr[], int N)
{
    int leftProduct = 1;
    int rightProduct = 1;
    for (int i = 0; i < N; i++) {
        // calculate product of elements from 0 to i
        leftProduct *= arr[i];
 
        // calculate product of elements from i+1 to N-1
        for (int j = i + 1; j < N; j++) {
            rightProduct *= arr[j];
        }
 
        // if the product of the two subarrays is equal,
        // return i
        if (leftProduct == rightProduct) {
            cout << i + 1 << endl;
            return;
        }
 
        // reset rightProduct for the next iteration
        rightProduct = 1;
    }
 
    // if no such index is found, return -1
    cout << -1 << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    prodEquilibrium(arr, N);
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
    // Function to find the smallest index that splits the
    // array into two subarrays with equal product
    static void prodEquilibrium(int[] arr, int N)
    {
        int leftProduct = 1;
        int rightProduct = 1;
        for (int i = 0; i < N; i++) {
            // calculate product of elements from 0 to i
            leftProduct *= arr[i];
 
            // calculate product of elements from i+1 to N-1
            for (int j = i + 1; j < N; j++) {
                rightProduct *= arr[j];
            }
 
            // if the product of the two subarrays is equal,
            // return i
            if (leftProduct == rightProduct) {
                System.out.println(i + 1);
                return;
            }
 
            // reset rightProduct for the next iteration
            rightProduct = 1;
        }
 
        // if no such index is found, return -1
        System.out.println(-1);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 3, 2, 1 };
        int N = arr.length;
        prodEquilibrium(arr, N);
    }
}
// This code is contributed by Prajwal Kandekar


Python3




def prodEquilibrium(arr, N):
    leftProduct = 1
    rightProduct = 1
    for i in range(N):
 
        # calculate product of elements from 0 to i
        leftProduct *= arr[i]
 
        # calculate product of elements from i+1 to N-1
        for j in range(i+1, N):
            rightProduct *= arr[j]
 
        # if the product of the two subarrays is equal, return i
        if leftProduct == rightProduct:
            print(i+1)
            return
 
        # reset rightProduct for the next iteration
        rightProduct = 1
 
    # if no such index is found, return -1
    print(-1)
 
 
# Driver Code
arr = [1, 2, 3, 3, 2, 1]
N = len(arr)
prodEquilibrium(arr, N)
 
# This code is contributed by Prajwal Kandekar


C#




using System;
 
public class Program
{
  // Function to find the smallest index that splits the array
  // into two subarrays with equal product
  public static void ProdEquilibrium(int[] arr, int N)
  {
    int leftProduct = 1;
    int rightProduct = 1;
    for (int i = 0; i < N; i++)
    {
      // calculate product of elements from 0 to i
      leftProduct *= arr[i];
 
      // calculate product of elements from i+1 to N-1
      for (int j = i + 1; j < N; j++)
      {
        rightProduct *= arr[j];
      }
 
      // if the product of the two subarrays is equal,
      // return i
      if (leftProduct == rightProduct)
      {
        Console.WriteLine(i + 1);
        return;
      }
 
      // reset rightProduct for the next iteration
      rightProduct = 1;
    }
 
    // if no such index is found, return -1
    Console.WriteLine("-1");
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { 1, 2, 3, 3, 2, 1 };
    int N = arr.Length;
    ProdEquilibrium(arr, N);
  }
}


Javascript




// Javascript code for the above approach
 
// Function to find the smallest index that splits the array into
// two subarrays with equal product
function prodEquilibrium(arr, N) {
    let leftProduct = 1;
    let rightProduct = 1;
    for (let i = 0; i < N; i++) {
         
        // calculate product of elements from 0 to i
        leftProduct *= arr[i];
     
        // calculate product of elements from i+1 to N-1
        for (let j = i + 1; j < N; j++) {
            rightProduct *= arr[j];
        }
     
        // if the product of the two subarrays is equal, return i
        if (leftProduct === rightProduct) {
            console.log(i + 1);
            return;
        }
     
        // reset rightProduct for the next iteration
        rightProduct = 1;
    }
 
    // if no such index is found, return -1
    console.log(-1);
}
 
// Driver Code
let arr = [1, 2, 3, 3, 2, 1];
let N = arr.length;
prodEquilibrium(arr, N);


Output

3

Time Complexity: O(N^2)

Space Complexity: O(1)
 

Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say product, > that stores the product of all the array elements.
  • Traverse the given array and find the product of all the array elements store it in the product.
  • Initialize two variables left and right to 1 that stores the product of the left and the right subarray
  • Traverse the given array and perform the following steps:
    • Multiply the value of left by arr[i].
    • Divide the value of right by arr[i].
    • If the value of left is equal to right, then print the value of the current index i as the resultant index and break out of the loop.
  • After completing the above steps, if any such index doesn’t exist, then print “-1” as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to find the smallest
// index that splits the array into
// two subarrays with equal product
void prodEquilibrium(int arr[], int N)
{
    // Stores the product of the array
    int product = 1;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
        product *= arr[i];
    }
 
    // Stores the product of left
    // and the right subarrays
    int left = 1;
    int right = product;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Update the products
        left = left * arr[i];
        right = right / arr[i];
 
        // Check if product is equal
        if (left == right) {
 
            // Print resultant index
            cout << i + 1 << endl;
            return;
        }
    }
 
    // If no partition exists, then
    // print -1.
    cout << -1 << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    prodEquilibrium(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the smallest
// index that splits the array into
// two subarrays with equal product
static void prodEquilibrium(int arr[], int N)
{
     
    // Stores the product of the array
    int product = 1;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
        product *= arr[i];
    }
 
    // Stores the product of left
    // and the right subarrays
    int left = 1;
    int right = product;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // Update the products
        left = left * arr[i];
        right = right / arr[i];
 
        // Check if product is equal
        if (left == right)
        {
             
            // Print resultant index
            System.out.print(i + 1 + "\n");
            return;
        }
    }
 
    // If no partition exists, then
    // print -1.
    System.out.print(-1 + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 3, 2, 1 };
    int N = arr.length;
     
    prodEquilibrium(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 program for the above approach
 
# Function to find the smallest
# index that splits the array into
# two subarrays with equal product
def prodEquilibrium(arr, N):
   
    # Stores the product of the array
    product = 1
 
    # Traverse the given array
    for i in range(N):
        product *= arr[i]
 
    # Stores the product of left
    # and the right subarrays
    left = 1
    right = product
 
    # Traverse the given array
    for i in range(N):
        # Update the products
        left = left * arr[i]
        right = right // arr[i]
 
        # Check if product is equal
        if (left == right):
            # Print resultant index
            print(i + 1)
            return
 
    # If no partition exists, then
    # print -1.
    print(-1)
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 3, 2, 1]
    N = len(arr)
    prodEquilibrium(arr, N)
     
    # This code is contributed by ipg2016107.


C#




// C# program for the above approach
using System;
class GFG {
 
    // Function to find the smallest
    // index that splits the array into
    // two subarrays with equal product
    static void prodEquilibrium(int[] arr, int N)
    {
 
        // Stores the product of the array
        int product = 1;
 
        // Traverse the given array
        for (int i = 0; i < N; i++) {
            product *= arr[i];
        }
 
        // Stores the product of left
        // and the right subarrays
        int left = 1;
        int right = product;
 
        // Traverse the given array
        for (int i = 0; i < N; i++) {
 
            // Update the products
            left = left * arr[i];
            right = right / arr[i];
 
            // Check if product is equal
            if (left == right) {
 
                // Print resultant index
                Console.WriteLine(i + 1 + "\n");
                return;
            }
        }
 
        // If no partition exists, then
        // print -1.
        Console.WriteLine(-1 + "\n");
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 3, 2, 1 };
        int N = arr.Length;
 
        prodEquilibrium(arr, N);
    }
}
 
 // This code is contributed by ukasp.


Javascript




<script>
// JavaScript program for the above approach
 
// Function to find the smallest
// index that splits the array into
// two subarrays with equal product
function prodEquilibrium(arr, N)
{
    // Stores the product of the array
    let product = 1;
 
    // Traverse the given array
    for (let i = 0; i < N; i++) {
        product *= arr[i];
    }
 
    // Stores the product of left
    // and the right subarrays
    let left = 1;
    let right = product;
 
    // Traverse the given array
    for (let i = 0; i < N; i++) {
 
        // Update the products
        left = left * arr[i];
        right = right / arr[i];
 
        // Check if product is equal
        if (left == right) {
 
            // Print resultant index
            document.write((i + 1) + "<br>");
            return;
        }
    }
 
    // If no partition exists, then
    // print -1.
    document.write((-1) + "<br>");
}
 
// Driver Code
 
    let arr = [ 1, 2, 3, 3, 2, 1 ];
    let N = arr.length;
    prodEquilibrium(arr, N);
     
    // This code is contributed by Dharanendra L V.
 
</script>


Output

3

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



Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads