Find an index such that difference between product of elements before and after it is minimum
Last Updated :
24 Nov, 2022
Given an integer arr[], the task is to find an index such that the difference between the product of elements up to that index (including that index) and the product of rest of the elements is minimum. If more than one such index is present, then return the minimum index as the answer.
Examples:
Input : arr[] = { 2, 2, 1 }
Output : 0
For index 0: abs((2) - (2 * 1)) = 0
For index 1: abs((2 * 2) - (1)) = 3
Input : arr[] = { 3, 2, 5, 7, 2, 9 }
Output : 2
A Simple Solution is to traverse through all elements starting from first to second last element. For every element, find the product of elements till this element (including this element). Then find the product of elements after it. Finally compute the difference. If the difference is minimum so far, update the result.
Better Approach: The problem can be easily solved using a prefix product array prod[] where the prod[i] stores the product of elements from arr[0] to arr[i]. Therefore, the product of rest of the elements can be easily found by dividing the total product of the array by the product up to current index. Now, iterate the product array to find the index with minimum difference.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
// Function to return the index i such that
// the absolute difference between product
// of elements up to that index and the
// product of rest of the elements
// of the array is minimum
int findIndex(int a[], int n)
{
// To store the required index
int res;
ll min_diff = INT_MAX;
// Prefix product array
ll prod[n];
prod[0] = a[0];
// Compute the product array
for (int i = 1; i < n; i++)
prod[i] = prod[i - 1] * a[i];
// Iterate the product array to find the index
for (int i = 0; i < n - 1; i++) {
ll curr_diff = abs((prod[n - 1] / prod[i]) - prod[i]);
if (curr_diff < min_diff) {
min_diff = curr_diff;
res = i;
}
}
return res;
}
// Driver code
int main()
{
int arr[] = { 3, 2, 5, 7, 2, 9 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << findIndex(arr, N);
return 0;
}
Java
// Java implementation of the approach
class GFG{
// Function to return the index i such that
// the absolute difference between product
// of elements up to that index and the
// product of rest of the elements
// of the array is minimum
static int findIndex(int a[], int n)
{
// To store the required index
int res = 0;
long min_diff = Long.MAX_VALUE;
// Prefix product array
long prod[] = new long[n];
prod[0] = a[0];
// Compute the product array
for (int i = 1; i < n; i++)
prod[i] = prod[i - 1] * a[i];
// Iterate the product array to find the index
for (int i = 0; i < n - 1; i++)
{
long curr_diff = Math.abs((prod[n - 1] /
prod[i]) - prod[i]);
if (curr_diff < min_diff)
{
min_diff = curr_diff;
res = i;
}
}
return res;
}
// Driver code
public static void main(String arg[])
{
int arr[] = { 3, 2, 5, 7, 2, 9 };
int N = arr.length;
System.out.println(findIndex(arr, N));
}
}
// This code is contributed by rutvik_56
Python3
# Python3 implementation of the approach
# Function to return the index i such that
# the absolute difference between product of
# elements up to that index and the product of
# rest of the elements of the array is minimum
def findIndex(a, n):
# To store the required index
res, min_diff = None, float('inf')
# Prefix product array
prod = [None] * n
prod[0] = a[0]
# Compute the product array
for i in range(1, n):
prod[i] = prod[i - 1] * a[i]
# Iterate the product array to find the index
for i in range(0, n - 1):
curr_diff = abs((prod[n - 1] // prod[i]) - prod[i])
if curr_diff < min_diff:
min_diff = curr_diff
res = i
return res
# Driver code
if __name__ == "__main__":
arr = [3, 2, 5, 7, 2, 9]
N = len(arr)
print(findIndex(arr, N))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the index i such that
// the absolute difference between product
// of elements up to that index and the
// product of rest of the elements
// of the array is minimum
static int findIndex(int[] a, int n)
{
// To store the required index
int res = 0;
long min_diff = Int64.MaxValue;
// Prefix product array
long[] prod = new long[n];
prod[0] = a[0];
// Compute the product array
for (int i = 1; i < n; i++)
prod[i] = prod[i - 1] * a[i];
// Iterate the product array to find the index
for (int i = 0; i < n - 1; i++)
{
long curr_diff = Math.Abs((prod[n - 1] /
prod[i]) - prod[i]);
if (curr_diff < min_diff)
{
min_diff = curr_diff;
res = i;
}
}
return res;
}
// Driver code
static void Main()
{
int[] arr = { 3, 2, 5, 7, 2, 9 };
int N = arr.Length;
Console.WriteLine(findIndex(arr, N));
}
}
// This code is contributed by divyeshrabadiya07
PHP
<?php
// PHP implementation of the approach
// Function to return the index i such that
// the absolute difference between product
// of elements up to that index and the
// product of rest of the elements
// of the array is minimum
function findIndex($a, $n)
{
$min_diff = PHP_INT_MAX;
// Prefix product array
$prod = array();
$prod[0] = $a[0];
// Compute the product array
for ($i = 1; $i < $n; $i++)
$prod[$i] = $prod[$i - 1] * $a[$i];
// Iterate the product array to find the index
for ($i = 0; $i < $n - 1; $i++)
{
$curr_diff = abs(($prod[$n - 1] /
$prod[$i]) - $prod[$i]);
if ($curr_diff < $min_diff)
{
$min_diff = $curr_diff;
$res = $i;
}
}
return $res;
}
// Driver code
$arr = array( 3, 2, 5, 7, 2, 9 );
$N = count($arr);
echo findIndex($arr, $N);
// This code is contributed by AnkitRai01
?>
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the index i such that
// the absolute difference between product
// of elements up to that index and the
// product of rest of the elements
// of the array is minimum
function findIndex(a, n)
{
// To store the required index
let res = 0;
let min_diff = Number.MAX_VALUE;
// Prefix product array
let prod = new Array(n);
prod[0] = a[0];
// Compute the product array
for (let i = 1; i < n; i++)
prod[i] = prod[i - 1] * a[i];
// Iterate the product array to find the index
for (let i = 0; i < n - 1; i++)
{
let curr_diff = Math.abs(parseInt(prod[n - 1] / prod[i], 10) - prod[i]);
if (curr_diff < min_diff)
{
min_diff = curr_diff;
res = i;
}
}
return res;
}
let arr = [ 3, 2, 5, 7, 2, 9 ];
let N = arr.length;
document.write(findIndex(arr, N));
// This code is contributed by suresh07.
</script>
Time Complexity: O(N), where n is the size of the given array.
Auxiliary Space: O(N), where n is the size of the given array.
Approach without overflow
The above solution might cause overflow. To prevent overflow problem, Take log of all the values of the array. Now, question is boiled down to divide array in two halves with absolute difference of sum is minimum possible. Now, array contains log values of elements at each index. Maintain a prefix sum array B which holds sum of all the values till index i. Check for all the indexes, abs(B[n-1] - 2*B[i]) and find the index with minimum possible absolute value.
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Function to find index
void solve(int Array[], int N)
{
// Array to store log values of elements
double Arraynew[N];
for (int i = 0; i < N; i++) {
Arraynew[i] = log(Array[i]);
}
// Prefix Array to Maintain Sum of log values till index i
double prefixsum[N];
prefixsum[0] = Arraynew[0];
for (int i = 1; i < N; i++) {
prefixsum[i] = prefixsum[i - 1] + Arraynew[i];
}
// Answer Index
int answer = 0;
double minabs = abs(prefixsum[N - 1] - 2 * prefixsum[0]);
for (int i = 1; i < N - 1; i++) {
double ans1 = abs(prefixsum[N - 1] - 2 * prefixsum[i]);
// Find minimum absolute value
if (ans1 < minabs) {
minabs = ans1;
answer = i;
}
}
cout << "Index is: " << answer << endl;
}
// Driver Code
int main()
{
int Array[5] = { 1, 4, 12, 2, 6 };
int N = 5;
solve(Array, N);
}
Java
public class Main
{
// Function to find index
public static void solve(int Array[], int N)
{
// Array to store log values of elements
double Arraynew[] = new double[N];
for (int i = 0; i < N; i++) {
Arraynew[i] = Math.log(Array[i]);
}
// Prefix Array to Maintain Sum of log values till index i
double prefixsum[] = new double[N];
prefixsum[0] = Arraynew[0];
for (int i = 1; i < N; i++)
{
prefixsum[i] = prefixsum[i - 1] + Arraynew[i];
}
// Answer Index
int answer = 0;
double minabs = Math.abs(prefixsum[N - 1] - 2 *
prefixsum[0]);
for (int i = 1; i < N - 1; i++)
{
double ans1 = Math.abs(prefixsum[N - 1] - 2 *
prefixsum[i]);
// Find minimum absolute value
if (ans1 < minabs)
{
minabs = ans1;
answer = i;
}
}
System.out.println("Index is: " + answer);
}
// Driver code
public static void main(String[] args)
{
int Array[] = { 1, 4, 12, 2, 6 };
int N = 5;
solve(Array, N);
}
}
// This code is contributed by divyesh072019
Python3
import math
# Function to find index
def solve( Array, N):
# Array to store log values of elements
Arraynew = [0]*N
for i in range( N ) :
Arraynew[i] = math.log(Array[i])
# Prefix Array to Maintain Sum of log values till index i
prefixsum = [0]*N
prefixsum[0] = Arraynew[0]
for i in range( 1, N) :
prefixsum[i] = prefixsum[i - 1] + Arraynew[i]
# Answer Index
answer = 0
minabs = abs(prefixsum[N - 1] - 2 * prefixsum[0])
for i in range(1, N - 1):
ans1 = abs(prefixsum[N - 1] - 2 * prefixsum[i])
# Find minimum absolute value
if (ans1 < minabs):
minabs = ans1
answer = i
print("Index is: " ,answer)
# Driver Code
if __name__ == "__main__":
Array = [ 1, 4, 12, 2, 6 ]
N = 5
solve(Array, N)
# This code is contributed by chitranayal
C#
using System;
using System.Collections;
class GFG{
// Function to find index
public static void solve(int []Array, int N)
{
// Array to store log values of elements
double []Arraynew = new double[N];
for(int i = 0; i < N; i++)
{
Arraynew[i] = Math.Log(Array[i]);
}
// Prefix Array to Maintain Sum of
// log values till index i
double []prefixsum = new double[N];
prefixsum[0] = Arraynew[0];
for(int i = 1; i < N; i++)
{
prefixsum[i] = prefixsum[i - 1] +
Arraynew[i];
}
// Answer Index
int answer = 0;
double minabs = Math.Abs(prefixsum[N - 1] - 2 *
prefixsum[0]);
for(int i = 1; i < N - 1; i++)
{
double ans1 = Math.Abs(prefixsum[N - 1] - 2 *
prefixsum[i]);
// Find minimum absolute value
if (ans1 < minabs)
{
minabs = ans1;
answer = i;
}
}
Console.WriteLine("Index is: " + answer);
}
// Driver code
public static void Main(string []args)
{
int []Array = { 1, 4, 12, 2, 6 };
int N = 5;
solve(Array, N);
}
}
// This code is contributed by pratham76
JavaScript
<script>
// Function to find index
function solve(array, N)
{
// Array to store log values of elements
let Arraynew = new Array(N);
for(let i = 0; i < N; i++)
{
Arraynew[i] = Math.log(array[i]);
}
// Prefix Array to Maintain Sum of
// log values till index i
let prefixsum = new Array(N);
prefixsum[0] = Arraynew[0];
for(let i = 1; i < N; i++)
{
prefixsum[i] = prefixsum[i - 1] +
Arraynew[i];
}
// Answer Index
let answer = 0;
let minabs = Math.abs(prefixsum[N - 1] - 2 *
prefixsum[0]);
for(let i = 1; i < N - 1; i++)
{
let ans1 = Math.abs(prefixsum[N - 1] - 2 *
prefixsum[i]);
// Find minimum absolute value
if (ans1 < minabs)
{
minabs = ans1;
answer = i;
}
}
document.write("Index is: " + answer + "</br>");
}
let array = [ 1, 4, 12, 2, 6 ];
let N = 5;
solve(array, N);
</script>
Time Complexity: O(N), where n is the size of the given array.
Auxiliary Space: O(N), where n is the size of the given array.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem